Swagger, now known as the OpenAPI Specification, has become the industry standard for documenting REST APIs. This guide will walk you through Swagger JSON examples, best practices, and tools to streamline your API documentation process.
Swagger is a set of rules, specifications, and tools for developing web APIs. It allows developers to describe the structure of their APIs in a simple yet powerful JSON format. The Swagger specification enables tools to automatically generate documentation, client SDKs, and server stubs from a simple definition file.
A basic Swagger JSON file starts with essential information about your API. Here's a minimal example:
{
"swagger": "2.0",
"info": {
"title": "Sample API",
"version": "1.0.0",
"description": "A sample API for demonstration purposes"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": ["https"],
"paths": {},
"definitions": {}
}Once you've established the basic structure, you can add API endpoints under the "paths" object. Here's an example with a simple GET endpoint:
{
"swagger": "2.0",
"info": {
"title": "Sample API",
"version": "1.0.0",
"description": "A sample API for demonstration purposes"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": ["https"],
"paths": {
"/users": {
"get": {
"summary": "List all users",
"description": "Returns a list of all users in the system",
"operationId": "listUsers",
"responses": {
"200": {
"description": "A list of users",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
}
}
}
},
"definitions": {
"User": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 123
},
"name": {
"type": "string",
"example": "John Doe"
},
"email": {
"type": "string",
"format": "email",
"example": "john.doe@example.com"
}
}
}
}
}Real-world APIs typically have multiple endpoints. Here's an expanded example with POST, PUT, and DELETE operations:
{
"swagger": "2.0",
"info": {
"title": "E-commerce API",
"version": "1.0.0",
"description": "API for managing products, orders, and customers"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": ["https"],
"securityDefinitions": {
"apiKey": {
"type": "apiKey",
"name": "X-API-Key",
"in": "header"
}
},
"security": [{
"apiKey": []
}],
"paths": {