OpenAPI
What is OpenAPI?
Section titled “What is OpenAPI?”- OpenAPI (formerly known as Swagger) is a specification for describing REST APIs.
- It’s like a blueprint that tells developers exactly how your API works: what endpoints are available, what data they expect, and what they return.
- Think of it as a user manual for your API that both humans and computers can understand.
- OpenAPI specifications are written in YAML (or JSON) format and follow a specific structure.
Resources for Further Learning
Section titled “Resources for Further Learning”- OpenAPI Specification ↗ - Official documentation.
- Swagger Documentation ↗ - Comprehensive guides and tutorials.
Basic YAML Syntax Rules
Section titled “Basic YAML Syntax Rules”Before diving into OpenAPI, here are the YAML basics you’ll need:
- Indentation matters: Use 2 spaces (not tabs) for each level.
- Key-value pairs:
key: value - Lists: Use hyphens (
-) for array items. - Strings: Can be quoted or unquoted (quote when containing special characters).
- Comments: Start with
#
OpenAPI File Structure
Section titled “OpenAPI File Structure”Every OpenAPI specification follows this structure. Here’s a complete example:
openapi: 3.2.0info: title: My Planets API description: A simple API for managing planetary data version: 1.0.0servers: - url: https://api.space-research.com/v1 description: Production serverpaths: /planets: get: summary: Get all planets responses: '200': description: Successful response content: application/json: schema: type: array items: $ref: '#/components/schemas/Planet'components: schemas: Planet: type: object required: - id - name - system properties: id: type: integer example: 1 name: type: string example: "Earth" system: type: string example: "Solar System"Let’s walk through each section.
1. Info Section
Section titled “1. Info Section”Provides basic metadata about your API. Always specify a clear title, a brief description, and a version number (use semantic versioning ↗ like 1.0.0).
info: title: Your API Name description: What your API does version: 1.0.0 contact: name: Your Name email: your.email@example.com2. Servers Section
Section titled “2. Servers Section”Lists where your API is hosted. You can define multiple servers (e.g., production, staging, development).
servers: - url: https://api.example.com/v1 description: Production server - url: https://staging-api.example.com/v1 description: Staging server3. Paths Section (Your Endpoints)
Section titled “3. Paths Section (Your Endpoints)”This is the core of your specification. For each endpoint, define:
- The URI path (e.g.,
/planets,/planets/{id}) - HTTP methods (get, post, put, delete)
- Parameters: path parameters (like
{id}), query parameters (filters, pagination), and request bodies (for POST/PUT) - Responses: all possible HTTP status codes with their content types and schemas
paths: /planets/{id}: get: summary: Get planet by ID parameters: - name: id in: path required: true schema: type: integer responses: '200': description: Planet found '404': description: Planet not found4. Components Section
Section titled “4. Components Section”The components section is where you define reusable pieces of your specification. Instead of repeating the same definition in every endpoint, you define it once here and reference it with $ref. It can contain:
schemas: Data models (e.g.,Planet,ErrorResponse)parameters: Query or path parameters (e.g.,page,page_size)responses: Common error responses (e.g.,400 Bad Request,500 Internal Server Error)securitySchemes: Authentication methods (e.g., API keys, JWT tokens)
See the OpenAPI Example page for a detailed explanation and a complete example using components.
Common HTTP Methods
Section titled “Common HTTP Methods”GET - Retrieve Data
Section titled “GET - Retrieve Data”/planets: get: summary: Get all planets parameters: - name: limit in: query schema: type: integer default: 10POST - Create New Resource
Section titled “POST - Create New Resource”/planets: post: summary: Create a new planet requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/Planet'PUT - Update Entire Resource
Section titled “PUT - Update Entire Resource”/planets/{id}: put: summary: Update a planet parameters: - name: id in: path required: true schema: type: integerDELETE - Remove Resource
Section titled “DELETE - Remove Resource”/planets/{id}: delete: summary: Delete a planet parameters: - name: id in: path required: true schema: type: integerData Types and Validation
Section titled “Data Types and Validation”OpenAPI supports various data types with validation rules:
properties: age: type: integer minimum: 0 maximum: 150 email: type: string format: email website: type: string format: uri birthDate: type: string format: date rating: type: number minimum: 1.0 maximum: 5.0 tags: type: array items: type: stringAuthentication in OpenAPI
Section titled “Authentication in OpenAPI”API Key Authentication
Section titled “API Key Authentication”components: securitySchemes: ApiKeyAuth: type: apiKey in: header name: X-API-Key
security: - ApiKeyAuth: []Bearer Token (JWT)
Section titled “Bearer Token (JWT)”components: securitySchemes: BearerAuth: type: http scheme: bearer bearerFormat: JWTCommon Mistakes to Avoid
Section titled “Common Mistakes to Avoid”YAML Formatting Issues
Section titled “YAML Formatting Issues”- Inconsistent indentation: Always use 2 spaces.
- Missing colons: Every key needs a colon.
- Incorrect list formatting: Use proper hyphen alignment.
Content Problems
Section titled “Content Problems”- Missing required fields: Always mark required fields in your schemas.
- Inconsistent data types: Use the same type for the same data across endpoints.
- Missing examples: Always provide realistic examples.
- Incomplete error handling: Document all possible error scenarios.
- Vague descriptions: Write clear, specific descriptions for endpoints and parameters.
- Ignoring status codes: Document all possible HTTP response codes.
Design Issues
Section titled “Design Issues”- Non-RESTful patterns: Follow REST principles for consistency.
- Overly complex schemas: Keep data models simple and focused.
- Missing versioning: Always include API version information.
- Inconsistent naming: Use camelCase for properties and kebab-case for paths.
Development Checklist
Section titled “Development Checklist”Getting Started
Section titled “Getting Started”- Define your API’s basic info (title, version, description).
- List your server URIs.
- Document at least one GET endpoint.
- Create schemas for your main data models.
- Add request/response examples.
- Test your specification in Swagger Editor.
Quality Assurance (Before Submission)
Section titled “Quality Assurance (Before Submission)”- All endpoints have clear descriptions and realistic examples.
- Every response code is documented with appropriate schemas.
- Data models are complete with proper types and validations.
- Authentication requirements are clearly specified.
- Error responses include meaningful error messages.
- File validates without errors in VS Code extension.
- Specification renders properly in OpenAPI Playground.
- Generate documentation to share with others.