Swagger: GET command example

22 September, 2018

In this post I put together an example of defining a GET API command in Swagger. I cover defining URL and path of the API, list of parameters (path, query and header parameters) for the GET API command and the response body of the command.

To exercise the code I was using the Online Swagger Editor. The editor also can be downloaded from swagger.io web site. It is a node project and can be run locally:

git clone https://github.com/swagger-api/swagger-editor.git
cd swagger-editor/
npm install
npm start

Table of content:


Swagger is a framework and set of tools that use the OpenAPI Specification (OAS) for describing, producing, consuming, and visualizing REST-ful web services.

Swagger uses YAML as language to define the API contracts. Some basic YAML syntax I covered in a previous blog post.

In this example the GET API command is a part of a Product Catalog API with the following top-level information:

Product Catalog service.
Company: ProductCatalog.com
API base URL:
    https://api.ProductCatalog.com/v1

We have a “GET products” API command. Upon success we receive tax rate information, and a list of products with their id, title and pricing information.

curl -X GET "https://api.ProductCatalog.com/v1/products/123?userId=456" -H "accept: application/json" -H "api-sessionid: ABCDEF"

{
  "taxRate": 0.10,
  "products": [
    {
      "productId": 123,
      "productTitle": "Basic membership",
      "isoCurrencyCode": "USD",
      "productPrice": {
        "salesPrice": 1.00,
        "taxAmount": 0.10,
        "totalCost": 1.10
      }
    }
  ]
}

Specification file

We start with definition of the Product Catalog API in a file like this:

swagger: '2.0' # Every Open API file needs this

info:
  version: "0.0.1"
  title: Product Catalog service
  description: |
    The Product Catalog service provides products information, and allows purchasing of products.
host: api.ProductCatalog.com
basePath: /v1
tags:
  - name: products
    description: Lists of products, information about single product, etc.
  - name: purchase
    description: Purchasing products
schemes:
  - https

I added two tags to group service commands - “products” and “purchase”. I am adding the “GET products” API command to the “products” tag.

The online Swagger editor is composed of left side panel, where we enter the YAML code and right side panel, where we get error messages, hints and preview of the API. It also provides a simple generator of mock data inside the right side panel. In this case we have still work to do, as we do not have any paths defined:

Editor error

Path and request definition

Next I define the request for getting the list of all the products from the catalog. The request has:

  • URL endpoint
  • HTTP Method
  • Path parameters
  • Query parameters
  • Custom header parameters

In the URL I have both path parameter as well as query parameter:

GET https://api.ProductCatalog.com/v1/products/{ratecardId}?userId={userId}

And here is the definition of the path and method:

# Endpoints
paths:
  /products/{ratecardId}:
    get:
      tags:
        - products
      summary: |
        Get list of all products by ratecard ID.
      produces:
        - application/json
      parameters:
        # Sent as path parameter
        - name: ratecardId
          description: Ratecard ID
          in: path
          required: true
          type: integer

        # Sent as query parameter
        - name: userId
          description: User ID
          in: query
          required: true
          type: integer

        # Sent as header parameter
        - name: api-sessionid
          description: Session ID
          in: header
          required: false
          type: string

The response has to be defined using OAS schema. The OAS schema object is based off the JSON Schema Specification. With the OAS schema we define:

  • Key and value pairs
  • Type of the values

To simplify the structure of the YAML file, we are using a $ref reference. The $ref reference is a key which value points to a structure defined somewhere else in the YAML file.

Let’s say for example we have this $ref reference:

schema:
  $ref: '#/definitions/GetProductsResponse'

Then later in the file under definitions: we have this definition:

definitions:
  GetProductsResponse:
    properties:
      ...

And here finally are the definitions for http response code 200 and 400:

      # Response fields
      responses:
        '200':
          description: successful operation
          schema:
              $ref: '#/definitions/GetProductsResponse'
        '400':
          description: Invalid ratecardId or invalid userId

definitions:
    ProductPrice:
      description: Pricing information
      type: object
      properties:
        salesPrice:
          description: Sales price prior tax application
          type: number
          format: double
        taxAmount:
          description: Tax amount
          type: number
          format: double
        totalCost:
          description: Total cost after tax applied
          type: number
          format: double

    Product:
      type: object
      properties:
        productId:
          description: Product ID
          type: integer
        productTitle:
          description: Product title
          type: string
        isoCurrencyCode:
          description: Three letter ISO currency code
          type: string
        productPrice:
          $ref: '#/definitions/ProductPrice'

    GetProductsResponse:
      type: object
      properties:
        taxRate:
          description: Tax rate
          type: number
          format: double
          minimum: 0.0000
        products:
          type: array
          items:
            $ref: '#/definitions/Product'

Links

Download the code

Swagger

Online Swagger Editor

Downloadable Swagger Editor

OpenAPI Specification (OAS)

YAML

YAML basic syntax