How to define an API in swagger OpenAPI
Swagger
Swagger is a specification used to describe and define RESTful APIs. The Swagger ecosystem contains many auto generators both to and from code, documentation creators, user interface, and inspectors that allow us to test and develop the APIs. Swagger allows for both YAML and JSON formats to be used for specifications.
OpenAPI specification
The API specification includes information about the API, such as what it does, what input parameters it takes, and what it returns. OpenAPI develops an ecosystem using a common specification language that makes it easier to understand API services.
Writing an OpenAPI specification
The following code snippet defines a minimal specification for defining an API with a GET method. The API can either return a 200 response or a 404 response.
openapi: 3.0.0info:title: Test APIdescription: My Test APIcontact:name: Educative Answersurl: https://www.educative.io/answersversion: 1.0.0paths:/myapi:description: Test API for educative answersget:description: Operation to get the resourcesparameters:- in: queryname: namerequired: falseschema:type: stringexample: How to define an API in swaggerresponses:200:description: Successful Responsecontent:application/json:schema:type: arrayitems:properties:ID:type: integerexample: 1Name:type: stringexample: How to define an API in swagger404:description: Answer not found
Explanation
- Line 1: We specify the OpenAPI version number for the specification below.
- Line 2–8: We some metadata for the API definition.
- Line 9: The
pathskey specifies the URL for accessing the API. - Line 10: We declare the path
/myapi, followed by its description on line 11. - Line 12: We indicate the HTTP method followed by its description on line 13.
- Line 14–20: We define the input parameters, which can be query and path parameters.
- Line 21: We define the response formats.
- Line 22: The HTTP code
200indicates success and is followed by the success response structure (lines 24–35). - Line 36: The HTTP code
404indicates failure, followed by the not found response description on line 37. Similarly, each error code can define a different response.
Conclusion
OpenAPI specification gives the developers a common language of writing/understanding APIs. This answer only covers the basic structure of the specification. The specification is very powerful and can help communicate complex API definitions. Along with Swagger, this has become the de facto standard of the REST API development lifecycle.