Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Write Your First Swagger Document

Write Your First Swagger Document

Swagger (OpenAPI) is a specification and toolset for describing, generating, and visualizing RESTful web services.

Below, I will detail how to write your first Swagger document from scratch.

Swagger documents mainly use YAML or JSON format and define all aspects of the API, including:


Creation Steps

1. Create basic file structure

First, create a file named swagger.yaml or swagger.json file. This tutorial uses YAML format as an example because it is easier to read and write.

Example

openapi

:

3.0.0

info

:

  title

:

My First API

  description

:

This is a simple API example document.

  version

:

1.0.0

  contact

:

    name

:

API Support Team

    email

:

support

@

example.

com

    url

:

https

:

//www.example.com/support

servers

:

 

url

:

https

:

//api.example.com/v1

    description

:

Production environment

 

url

:

https

:

//dev-api.example.com/v1

    description

:

Development environment

2. Add basic document information

Example

openapi

:

3.0.0

info

:

  title

:

My First API

  description

:

This is a simple API example document.

  version

:

1.0.0

  contact

:

    name

:

API Support Team

    email

:

support

@

example.

com

    url

:

https

:

//www.example.com/support

servers

:

 

url

:

https

:

//api.example.com/v1

    description

:

Production environment

 

url

:

https

:

//dev-api.example.com/v1

    description

:

Development environment

3. Define paths and operations

Paths define the endpoints that the API can access, and operations define the HTTP methods (GET, POST, PUT, DELETE, etc.) that can be performed on these endpoints.

Example

paths

:

 

/

users

:

   

get

:

      summary

:

Get all user list

      description

:

Return all user information in the system

      operationId

:

getUsers

      parameters

:

       

name

:

limit

         

in

:

query

          description

:

Maximum number of returned results

          required

:

false

          schema

:

            type

:

integer

            format

:

int32

            minimum

:

1

            maximum

:

100

           

default

:

20

      responses

:

       

'200'

:

          description

:

Successfully retrieved user list

          content

:

            application

/

json

:

              schema

:

                type

:

array

                items

:

                  $ref

:

'#/components/schemas/User'

       

'400'

:

          description

:

Invalid request

          content

:

            application

/

json

:

              schema

:

                $ref

:

'#/components/schemas/Error'

    post

:

      summary

:

Create new user

      description

:

Create a new user in the system

      operationId

:

createUser

      requestBody

:

        description

:

User information

        required

:

true

        content

:

          application

/

json

:

            schema

:

              $ref

:

'#/components/schemas/NewUser'

      responses

:

       

'201'

:

          description

:

User created successfully

          content

:

            application

/

json

:

              schema

:

                $ref

:

'#/components/schemas/User'

       

'400'

:

          description

:

Invalid request

          content

:

            application

/

json

:

              schema

:

                $ref

:

'#/components/schemas/Error'

4. Define components and models

in components The section defines reusable models:

Example

components

:

  schemas

:

    User

:

      type

:

object

      properties

:

        id

:

          type

:

integer

          format

:

int64

          description

:

Unique user identifier

        username

:

          type

:

string

          description

:

Username

        email

:

          type

:

string

          format

:

email

          description

:

User email

        status

:

          type

:

string

         

enum

:

[

active

,

inactive

,

banned

]

          description

:

User status

        createdAt

:

          type

:

string

          format

:

date

time

          description

:

Creation time

      required

:

       

id

       

username

       

email

       

status

   

    NewUser

:

      type

:

object

      properties

:

        username

:

          type

:

string

          description

:

Username

        email

:

          type

:

string

          format

:

email

          description

:

User email

        password

:

          type

:

string

          format

:

password

          description

:

The user's password

          minLength

:

8

      required

:

       

username

       

email

       

password

   

    Error

:

      type

:

object

      properties

:

        code

:

          type

:

integer

          format

:

int32

        message

:

          type

:

string

      required

:

       

code

       

message

5. Add security definitions

Define the security requirements of the API:

Example

security

:

 

bearerAuth

:

[

]

components

:

  securitySchemes

:

    bearerAuth

:

      type

:

http

      scheme

:

bearer

      bearerFormat

:

JWT

6. Complete document example

Combine all the sections above and you get a complete Swagger document.

Example

openapi

:

3.0.0

info

:

  title

:

My First API

  description

:

This is a simple API example document.

  version

:

1.0.0

  contact

:

    name

:

API Support Team

    email

:

support

@

example.

com

    url

:

https

:

//www.example.com/support

servers

:

 

url

:

https

:

//api.example.com/v1

    description

:

Production environment

 

url

:

https

:

//dev-api.example.com/v1

    description

:

Development environment

paths

:

 

/

users

:

   

get

:

      summary

:

Get all user list

      description

:

Return all user information in the system

      operationId

:

getUsers

      parameters

:

       

name

:

limit

         

in

:

query

          description

:

Maximum number of returned results

          required

:

false

          schema

:

            type

:

integer

            format

:

int32

            minimum

:

1

            maximum

:

100

           

default

:

20

      responses

:

       

'200'

:

          description

:

Successfully retrieved user list

          content

:

            application

/

json

:

              schema

:

                type

:

array

                items

:

                  $ref

:

'#/components/schemas/User'

       

'400'

:

          description

:

Invalid request

          content

:

            application

/

json

:

              schema

:

                $ref

:

'#/components/schemas/Error'

    post

:

      summary

:

Create new user

      description

:

Create a new user in the system

      operationId

:

createUser

      requestBody

:

        description

:

User information

        required

:

true

        content

:

          application

/

json

:

            schema

:

              $ref

:

'#/components/schemas/NewUser'

      responses

:

       

'201'

:

          description

:

User created successfully

          content

:

            application

/

json

:

              schema

:

                $ref

:

'#/components/schemas/User'

       

'400'

:

          description

:

Invalid request

          content

:

            application

/

json

:

              schema

:

                $ref

:

'#/components/schemas/Error'

components

:

  schemas

:

    User

:

      type

:

object

      properties

:

        id

:

          type

:

integer

          format

:

int64

          description

:

Unique user identifier

        username

:

          type

:

string

          description

:

Username

        email

:

          type

:

string

          format

:

email

          description

:

User email

        status

:

          type

:

string

         

enum

:

[

active

,

inactive

,

banned

]

          description

:

User status

        createdAt

:

          type

:

string

          format

:

date

time

          description

:

Creation time

      required

:

       

id

       

username

       

email

       

status

    NewUser

:

      type

:

object

      properties

:

        username

:

          type

:

string

          description

:

Username

        email

:

          type

:

string

          format

:

email

          description

:

User email

        password

:

          type

:

string

          format

:

password

          description

:

The user's password

          minLength

:

8

      required

:

       

username

       

email

       

password

    Error

:

      type

:

object

      properties

:

        code

:

          type

:

integer

          format

:

int32

        message

:

          type

:

string

      required

:

       

code

       

message

  securitySchemes

:

    bearerAuth

:

      type

:

http

      scheme

:

bearer

      bearerFormat

:

JWT

security

:

 

bearerAuth

:

[

]

7. Use Swagger tools

There are multiple ways to visualize and test your Swagger document:

  1. Swagger UIAn interactive documentation page
  2. Swagger EditorAn online editor that previews documents in real time
  3. Swagger CodegenA tool for generating client code

8. Test your document online

You can use the Swagger Editor Test your document online. Simply copy and paste your YAML or JSON into the editor, and the right panel will display the visualized API documentation.

9. Best practices

10. Common parameter locations

Swagger defines several parameter locations:

11. Extend your documentation

As the API evolves, continue to extend your Swagger documentation:

12. Practical development integration

In actual development, you can: