0
0
Rest APIprogramming~5 mins

OpenAPI Specification (Swagger) in Rest API

Choose your learning style9 modes available
Introduction

OpenAPI Specification helps you describe your API clearly so others can understand and use it easily.

You want to share your API details with other developers.
You need to create automatic API documentation.
You want to test your API endpoints quickly.
You want to generate code or client libraries from your API.
You want to keep your API design consistent and clear.
Syntax
Rest API
openapi: 3.0.0
info:
  title: Sample API
  version: 1.0.0
paths:
  /items:
    get:
      summary: Get list of items
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: array
                items:
                  type: string

The specification is usually written in YAML or JSON format.

It starts with the OpenAPI version and includes info, paths, and components.

Examples
This example shows a simple GET endpoint that returns a greeting as plain text.
Rest API
openapi: 3.0.0
info:
  title: Simple API
  version: 1.0.0
paths:
  /hello:
    get:
      summary: Returns a greeting
      responses:
        '200':
          description: OK
          content:
            text/plain:
              schema:
                type: string
This is the same API written in JSON format, showing a POST endpoint to create a user.
Rest API
{
  "openapi": "3.0.0",
  "info": {
    "title": "JSON API",
    "version": "1.0.0"
  },
  "paths": {
    "/users": {
      "post": {
        "summary": "Create a user",
        "responses": {
          "201": {
            "description": "User created"
          }
        }
      }
    }
  }
}
Sample Program

This OpenAPI spec describes a GET endpoint at /books that returns a list of books with id, title, and author.

Rest API
openapi: 3.0.0
info:
  title: Book Store API
  version: 1.0.0
paths:
  /books:
    get:
      summary: List all books
      responses:
        '200':
          description: A list of books
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id:
                      type: integer
                    title:
                      type: string
                    author:
                      type: string
OutputSuccess
Important Notes

You can use tools like Swagger UI to turn this spec into interactive documentation.

Keep your API spec updated as your API changes to avoid confusion.

Summary

OpenAPI Specification describes APIs in a clear, standard way.

It helps with documentation, testing, and code generation.

You write it in YAML or JSON format with sections like info and paths.