Swagger

One of the biggest benefits of our highly connected digital world is the almost inexhaustible variety of information, knowledge and practical applications. For the latter, it is particularly true that a modern application can access, display and edit the corresponding resources via one or more interfaces. For this reason, these APIs are also subject to special requirements during project planning and development. Such an interface should be described as comprehensively as possible for all participants. This high level of transparency also helps in finding design and program errors.

Already in 2010 the eager programmer Tony Tam of Wordnik had big problems that for a structured description of a REST-API interface to be programmed by him the pure enumeration of the used URLs would not be sufficient. The necessary combination of different programming languages and technologies such as WSDL or WADL was also particularly difficult at this time. He found the solution in the definition of his own Interface Definition Language (IDL) for REST-API’s and called this Swagger, which is still available as Open Source under the Apache license. In 2015, the Swagger definition was renamed to the Open API Specification (OAS) as part of the newly established Open API Initiative (OAI).

API core elements in Swagger

The basis of an API description language always consists of the representation of the individual core elements such as the documentation, the access and end points as well as a detailed description of the used and possible error codes. The more detailed these core elements are described, the easier it is to use and maintain the API. Another important point is the security and thus also the security elements used in the interface. Decisive for the scope of functions are the business objects agreed in the API in the form of type declarations together with all parameters and return values ​​used.

The more precisely these specifications are described in the interface, the more transparent and simpler their application, maintenance and integration will be. For the description of these core elements we use as an example a fictitious user store, where a user can register and use the shop for his pet.

Docs

An important core element for the API is the Docs area. All text resources and documents relevant for the interface can be stored here as references. This can be a function description of the API, a developer documentation or a user manual for the users. For the description of a resource the two parameters description and url are available. The following short code snippet shows a possible application:

externalDocs:
  description: "Find out more about Swagger"
  url: "http://www.api-portal.io"

Details

The Details area contains all the important information about the entire interface. This basic information is therefore valid for the entire API. For the corresponding information, some parameters such as description, version, title or host are available. The most important parameters here are basePath and schemes. With basePath a versioning can be entered easily and clearly, by specifying the current directory here. Schemes lists the transfer protocols used for this API. The following source text section shows a possible parameterization:

info:
  description: "This is a sample server Userstore server."
  version: "1.0.0"
  title: "Swagger Users"
host: "users.api-portal.io"
basePath: "/v2"
schemes:
  - "http"

Note here the possibilities with the parameters basePath and version. Despite a version 1.0.0 in the parameter version, the base directory in the parameter basePath may be different.

Security

In an API interface also different authentication methods can be used. This makes it easy to share OAuth 2.0, Digest, and Pass-Through. Each authentication type has a set of required parameters such as type, name, scopes or flow. In the following example, we use OAuth 2.0 for authentication and describe its application in various parameters as follows:

securityDefinitions:
  userstore_auth:
    type: "oauth2"
    authorizationUrl: "http://users.api-portal.io/oauth/auth"
    flow: "implicit"
    scopes:
      write:users: "modify users in your account"
      read:users: "read your users"
  api_key:
    type: "apiKey"
    name: "api_key"
    in: "header"

In the parameter type we enter OAuth2 as authentication method and set the scope to the corresponding write and read methods. Via api_key we define the access key by name and its occurrence in header.

Resources

To access the host’s various resources through the HTTP protocol, the API first declares the most common access methods. These include the 4 standard method calls GET, POST, PUT and DELETE. Hereby the desired processing is signaled to the respective browser and how the attached parameters are to be used. Below you will find the four method calls with a brief explanation.

GET - Read access to a defined resource via the GET method. In our fictitious example of the user shop, a specific animal or product can be searched for and displayed afterwards. The sample call for this is simplified: GET /user/{userId}

POST - The POST method is used whenever a new but not existing resource is to be created. In our example we can easily insert a new pet with the following call: POST /user 2

PUT - Use this method to make a change to a resource already in the system. For our example, a change could be simplified as follows: PUT /user 2

DELETE - If a resource in inventory is no longer needed, it can be easily removed using the following method call. The identification is done here via the ID number as follows: DELETE /user/{userId}

The interaction of the methods and parameters is briefly described in the following code fragment. We assume that a registered user wants to search the stock for a previously defined pet. For this the userId is used.

/user/{userId}:
  get:
    tags:
      - "user"
    summary: "Find user by ID"
    description: "Returns a single user"
    operationId: "getUserById"
    produces:
      - "application/xml"
      - "application/json"
    parameters:
      - name: "userId"
        in: "path"
        description: "ID of user to return"
        required: true
        type: "integer"
        format: "int64"
    responses:
      200:
        description: "successful operation"
        schema:
          $ref: "#/definitions/User"
      400:
        description: "Invalid ID supplied"
      404:
        description: "User not found"
        security:
          - api_key: []

After the method call, the response code is also evaluated accordingly and shows via the 3 evaluation codes implemented here whether the query was successful or if the ID number could not be evaluated. The result can then be displayed formatted to the user.

Types

In the area of ​​types, all used articles: 205 [business objects] of the interface are now entered and managed. These objects can then be used again and again in different places within the API. The description of an object is carried out by its properties. To stay with our fictitious example of the user shop, you will find in the following source text the description of the user business object User with all parameter definitions:

definitions:
  User:
    type: "object"
    properties:
      id:
        type: "integer"
        format: "int64"
      username:
        type: "string"
      firstName:
        type: "string"
      lastName:
        type: "string"
      email:
        type: "string"
      password:
        type: "string"
      phone:
        type: "string"
      userStatus:
        type: "integer"
        format: "int32"
        description: "User Status"
        xml:
          name: "User"

An object property such as id is described in this source code using the type: and format: properties. The ID is thus an integer value in the format Int-64. All other properties are similarly defined until the object is fully described.

Errors

One of the most important definitions of an interface are the possible error or response codes. Using this, the API can make an evaluation of a method call and, in the event of errors, generate a plain text message for the user based on the error code. The declaration always follows the scheme {error code: description / message}. The following example shows the exact notation:

responses:
  200:
    description: "successful operation"
  400:
    description: "Invalid ID supplied"
  404:
    description: "Order not found"

Pros and Cons of Swagger

API development with Swagger offers some significant benefits. On the one hand, there are the widely used project approaches such as Code-First or Contract-/API-First. On the other hand, Swagger offers a language-neutral and above all machine-readable format. The definitions can be encoded in either JSON or YAML. In addition, Swagger also has a relatively simple extension approach. The development is supported by established tools such as the core library (swagger core), the Swagger UI for testing and visualization, the powerful Swagger editor and the code generator (Swagger codegen). Another plus is the huge community and the many code snippets for almost all use cases.

However, Swagger can not flexibly reuse code snippets compared to its competitors. Therefore includes or extensions are not reusable, which means significant additional expenses and thus a disadvantage in the programming of the API. In some aspects, such as server specifications or security, Swagger can no longer keep up with the new OpenAPI specification 3. Content negotiation and the expansion of the JSON schema are further plus points for the more modern API description language.

Conclusion

Especially in the area of ​​the RESTful APIs and the two widely used project approaches Code-First and Contract- / API-First, Swagger is a very good choice. The large community and the numerous tools available for almost all programming languages ​​provide an extremely broad and professional basis for the development of interfaces. The transformation from Swagger to the OpenAPI initiative in the current version 3.0, however, brings many new features and advantages. Several hosts and a much clearer structure support the revised version. With the new OpenAPI specification in the current version 3.0 and the broad support of the well-known manufacturers in the new initiative, however, OpenAPI 3.0 will prevail in the near future and gradually replace Swagger 2.0. Also in the area of tools and code generators, there is still some catching up to do for the OAS, which is ultimately only a matter of time.

API Developer Portal

Turn your ideas into reality, prototype, collaborate and turn them into incredible products with the digital API asset management platform.

Newsletter

The latest API Portal news, articles, and resources, sent straight to your inbox.

The privacy of your data is an important concern. For more informations, see the Privacy Policy

Copyright © 2023 dataliquid GmbH - All rights reserved.