Writing a swagger.json file
Tags: php, node, python, javascript
Published: 2020-06-22 10:08:57

Swagger is a tool that you can use to document and consume API. The document can be in `JSON` or `YAML` format.

In this tutorial, we will document [JSONPlaceholder](https://jsonplaceholder.typicode.com/) endpoints using Swagger and finally, we will consume JSONPlaceholder endpoints using Swagger UI.

## Initial Setup

I will recommend using Visual Studio Code as your editor for writing `Swagger` file with the below-mentioned extension as it helps in autocompletion:

* [OpenAPI (Swagger) Editor
](https://marketplace.visualstudio.com/items?itemName=42Crunch.vscode-openapi)

Let's start by creating a new file you can name it whatever you want but I will call it `swagger.json`. Now open that file in Visual Studio Code and put below text inside of it:

```json
{
  "openapi": "3.0.3",
  "info": {
    "title": "JSONPlaceholder",
    "description": "Fake Online REST API for Testing and Prototyping",
    "version": "0.0.1"
  },
  "paths": {}
}
```

Lets breakdown the above JSON into multiple parts:

* `openapi`: Swagger uses OpenAPI specifications which defines Swagger file structure
* `info`: Information about `JSONPlaceholder`
  * `title`: Our API name
  * `description`: Short description of our API
  * `version`: Version of the swagger file
* `paths`: All endpoints of any API

## JSONPlaceholder `/posts` endpoint

Now navigate to `swagger.json` and put the following conten in the `paths` key:

```json
"/posts": {
  "get": {
    "description": "List all posts",
    "responses": {}
  }
}
```

Lets breakdown the above JSON into multiple parts for your understanding:

* `"/posts"`: Endpoint to JSONPlaceholder which returns the list of posts
  * `"get"`: HTTP method of `/posts` endpoint
    * `"description"`: Short description of this endpoint
    * `"responses"`: List of possible responses that could come from this endpoint

Inside your browser open the following [link](https://jsonplaceholder.typicode.com/posts). You will see the array of posts.

As we know now that if everything is working fine on the `JSONPlaceholder` side we receive the list of posts. Now go back to our `swagger.json` file and replace `"responses": {}` with the following text:

```json
"responses": {
  "200": {
    "description": "Successfully fetched all posts from JSONPlaceholder",
    "content": {
      "application/json": {
        "schema": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "userId": {
                "type": "number"
              },
              "id": {
                "type": "number"
              },
              "title": {
                "type": "string"
              },
              "body": {
                "type": "string"
              }
            },
            "example": {
              "userId": 1,
              "id": 1,
              "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
              "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
            }
          }
        }
      }
    }
  }
}
```

Lets breakdown the above JSON:

* `"200"`: HTTP method of the success response
  * `"description"`: Short description of this response
  * `"content"`: Response that is coming from the server
    * `"application/json"`: Type of the response from server
      * `"schema"`: Data structure of the response from server
        * `"type"`: Data type of the received Data structure: `object`, `number`, `string`, `boolean`
          * `"items"`: Array item structure
            * `"type"`: Type of the array item: `object`, `number`, `string`, `boolean`
            * `"properties"`: Properties inside the post object
              * `"property"`: Property inside the post object
                * `"type"`: Type of the property: `object`, `number`, `string`, `boolean`
            * `"example"`: Example of the structure of a post item

Here is the full example of `swagger.json` file:

```json
{
  "openapi": "3.0.2",
  "info": {
    "title": "JSONPlaceholder",
    "description": "Fake Online REST API for Testing and Prototyping",
    "version": "0.0.1"
  },
  "paths": {
    "/posts": {
      "get": {
        "description": "List all posts",
        "responses": {
          "200": {
            "description": "Successfully fetched all posts from JSONPlaceholder",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "userId": {
                        "type": "number"
                      },
                      "id": {
                        "type": "number"
                      },
                      "title": {
                        "type": "string"
                      },
                      "body": {
                        "type": "string"
                      }
                    },
                    "example": {
                      "userId": 1,
                      "id": 1,
                      "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
                      "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

```