How to write a YAML file for Swagger UI
Swagger UI is a powerful tool for documenting and testing APIs. It allows us to visualize and interact with the endpoints of an API, making it an essential component for ensuring the usability and understanding of our API. We need a well-structured and informative documentation.yaml file to make the most out of Swagger UI. In this Answer, we’ll go through the process of creating a documentation.yaml file for Swagger UI.
Note: Click here to learn how to build a RESTful API.
Understanding the basics
Before we start crafting our documentation.yaml file, it’s crucial to clearly understand the structure and purpose of Swagger documentation. Swagger uses YAML or JSON files to define API specifications. These files provide information about the API’s endpoints, request and response formats, and other critical details.
The documentation.yaml file serves as the blueprint for our API’s documentation, helping users to understand and interact with our API effortlessly.
Writing a documentation.yaml file for Swagger UI
Follow the steps given below to write the documentation.yaml file for the Swagger UI:
Step 1: Specify swagger specification, info, and server section
The swagger specification is a standard for documenting RESTful APIs. It allows us to define our API’s endpoints, request parameters, and response formats. Swagger UI is built around this specification. We’ll start the documentation.yaml file by adding the following information:
OpenAPI version: The
openapifield specifies the swagger specification version, such as OpenAPI3.0.0. We’ll use a compatible version of the specification.Information section (Info): The
infosection provides general information about our API. Replace the title, description, and version with specific details about our API. This information will be displayed in our Swagger UI.Servers section: The
serverssection defines the base URL where our API is hosted. We can provide multiple entries under theserverssection if our API is hosted on multiple servers. We’ll replacehttps://Appwith our actual API URL.
openapi: 3.0.0info:title: Your API Titledescription: Single-line or multiline description of the API.version: 1.0.0servers:- url: "https://App"
Step 2: Define endpoints
In the paths section, we define the different routes of our API. For each of the endpoints in our API, we’ll add the following information:
HTTP method: Specify the HTTP method (e.g.,
GET,POST,PUT) and provide relevant details.Description: We describe what each route does in the
descriptionfield. This helps users understand the purpose of the route.Parameters: For routes that accept parameters, we define them under the
parameterssection. Include details like parameter name, location (e.g., query, path), and data type.Request Body (if applicable): We specify the structure of the request body if the route expects one. Make sure to reference the corresponding schema defined in the
componentssection (We will discusscomponentssection in Step 3).Responses: We define the possible responses for each route, including the
HTTPstatus code, a description, and the expected response structure.
paths:/endpoint:httpMethod:summary: Retrieve datadescription: Retrieve data from the API.parameters:- name: limitin: querydescription: The maximum number of items to returnrequired: falseschema:type: integerrequestBody:content:application/json:schema:type: objectproperties:name:type: stringage:type: integerresponses:'200':description: Successful responsecontent:application/json:schema:type: objectproperties:message:type: string
Step 2(a): Provide examples (optional)
Consider adding examples for request and response payloads to provide more context. We can do this by including them in the example section or by using the example keyword directly under the content type.
This makes it easier for users to understand how to interact with our API.
requestBody:content:application/json:schema:type: objectproperties:name:type: stringage:type: integerexample:name: John Doeage: 30responses:'200':description: Successful responsecontent:application/json:schema:type: objectproperties:message:type: stringexample:message: Data retrieved successfully
Step 3: Components section (optional)
The components section is used to define reusable schemas for request and response bodies. We can define schemas for our data objects and reference them accurately in our routes. In the code given under the Declaration tab, common definitions of SchemaName1, SchemaName2 objects are placed in the global components section and are referred to using $ref under the Usage tab.
components:schemas:SchemaName1:type: "object"properties:PropertyName1:type: "string"PropertyName2:type: "integer"SchemaName2:type: "object"properties:PropertyName1:type: "string"PropertyName2:type: "boolean"
Step 4: Validation (optional)
After creating or updating our documentation.yaml file, we’ll validate it using an OpenAPI validator or the Swagger Editor to ensure it adheres to the OpenAPI Specification and to check for any errors.
Step 5: Security (optional)
We can further customize our Swagger documentation by adding information such as authentication mechanisms, security definitions, or additional metadata specific to our API. In the code below, we define different security schemes to be used by the API in the global components/securitySchemes section. We then apply them to the whole API by adding the security section on the root level. This will apply the specified security schemes globally to all API operations.
components:securitySchemes:BasicAuth:type: httpscheme: basicApiKeyAuth:type: apiKeyin: headername: X-API-Keysecurity:- ApiKeyAuth: []- OAuth2:- read- write
Step 6: Customize and enhance (optional)
Moreover, Swagger provides a range of customization options to make our documentation visually appealing and user-friendly. We can define themes, colors, and more.
x-logo:url: https://example.com/logo.pngx-theme:name: custom-themebrandColor: '#FF5733'
Step 7: Testing
We’ll use Swagger UI to test our API before publishing our documentation.yaml file. This would help ensure that our documentation aligns with the actual functionality of our API.
Sample YAML File
Let's take a look at a Swagger UI documentation.yaml file for a sample Educative API.
openapi: 3.0.0info:title: Educative APIdescription: This is a sample Educative API.version: 1.0.0servers:- url: "https://EducativeAPI"paths:/users:get:summary: Get a list of usersdescription: Get a list of users from the API.responses:'200':description: Successful responsecontent:application/json:example:users:- id: 1name: John Doe- id: 2name: Jane Doepost:summary: Create a new userdescription: Add a new user information using the API.requestBody:required: truecontent:application/json:example:name: New Userresponses:'201':description: User created successfully/users/{id}:get:summary: Get user by IDdescription: Get a single user from the API.parameters:- in: pathname: idrequired: trueschema:type: integerresponses:'200':description: Successful responsecontent:application/json:example:id: 1name: John Doe'404':description: User not found
Conclusion
Creating a documentation.yaml file for Swagger UI is a crucial step in making our API accessible and easy to understand for developers and users. By following the steps above and adhering to the Swagger specification, we can produce comprehensive and well-structured documentation that enhances the usability of our API. Make sure to keep our documentation.yaml file up-to-date as our API evolves, providing users with accurate and helpful information at all times.
Free Resources