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.
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.
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
paths
key specifies the URL for accessing the API. /myapi
, followed by its description on line 11. 200
indicates success and is followed by the success response structure (lines 24–35). 404
indicates failure, followed by the not found response description on line 37. Similarly, each error code can define a different response.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.