Document Your API with Swagger/OpenAPI
Table of Contents
- Introduction
- Why Use Swagger/OpenAPI?
- ASP.NET Example
- Spring Boot Example
- Express.js Example
- Next.js Example
- Flask Example
- Laravel Example
- Swagger vs Postman Collections
- Best Practices
- Conclusion
Introduction
When building APIs, clear and consistent documentation is essential. Swagger (now part of the OpenAPI Specification) is the industry standard for documenting APIs. It provides an interactive interface where developers can explore endpoints, understand request/response structures, and even test APIs directly.
Why Use Swagger/OpenAPI?
- Improves developer experience with interactive docs.
- Ensures consistency across different teams.
- Can auto-generate client SDKs and server stubs.
- Acts as a single source of truth for API behavior.
ASP.NET Example
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapGet("/hello", () => "Hello World!");
app.Run();In ASP.NET, you enable Swagger by registering it in Program.cs. The UseSwaggerUI() middleware generates a UI at /swagger.
Spring Boot Example
// build.gradle
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
// Controller
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}With springdoc-openapi, Swagger UI is automatically available at /swagger-ui.html.
Express.js Example
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const app = express();
const swaggerSpec = swaggerJsDoc({
definition: {
openapi: '3.0.0',
info: { title: 'API Docs', version: '1.0.0' }
},
apis: ['./index.js'],
});
/**
* @swagger
* /hello:
* get:
* summary: Returns Hello
* responses:
* 200:
* description: Success
*/
app.get('/hello', (req, res) => res.send('Hello World!'));
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.listen(3000, () => console.log('Server running'));In Express.js, Swagger is integrated with swagger-jsdoc and swagger-ui-express. Documentation lives at /api-docs.
Next.js Example
// pages/api/swagger.js
import swaggerJsdoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
const swaggerSpec = swaggerJsdoc({
definition: {
openapi: '3.0.0',
info: { title: 'Next.js API Docs', version: '1.0.0' }
},
apis: ['./pages/api/*.js'],
});
export default function handler(req, res) {
res.status(200).json(swaggerSpec);
}
// You can serve the Swagger UI using a custom Next.js server or middlewareIn Next.js, you generate the OpenAPI spec inside an API route, then serve Swagger UI via a custom server or a separate route.
Flask Example
from flask import Flask
from flasgger import Swagger
app = Flask(__name__)
swagger = Swagger(app)
@app.route('/hello')
def hello():
"""
A Hello World endpoint.
---
responses:
200:
description: Returns a greeting
"""
return "Hello World!"
if __name__ == '__main__':
app.run()Flask developers can use flasgger to auto-generate Swagger docs at /apidocs.
Laravel Example
// Install package
composer require "darkaonline/l5-swagger"
// config/l5-swagger.php is generated after publishing config
// routes/api.php
Route::get('/hello', function () {
return response()->json(['message' => 'Hello World!']);
});Laravel developers often use the l5-swagger package to auto-generate docs. Swagger UI is available at /api/documentation.
Swagger vs Postman Collections
Both Swagger/OpenAPI and Postman Collections are widely used for API documentation and testing, but they serve slightly different purposes:
| Feature | Swagger/OpenAPI | Postman Collections |
|---|---|---|
| Purpose | Standardized, machine-readable API specification. | Testing and sharing API requests. |
| Format | JSON or YAML (OpenAPI Spec). | JSON collection file. |
| Strength | Code generation, live docs, contracts. | Easy collaboration, request testing. |
| Best Use Case | Designing and documenting APIs. | Team collaboration and testing workflows. |
Many teams use both: Swagger/OpenAPI for official API docs and Postman for collaboration and testing.
Best Practices for API Documentation
- Keep Documentation Updated: Your Swagger docs should evolve with your API. Automate generation wherever possible.
- Use Versioning: Maintain separate Swagger files for v1, v2, etc. to avoid confusion.
- Secure Swagger UI: Don’t expose docs in production without authentication. Limit access to trusted users.
- Be Descriptive: Include examples, detailed error messages, and clear summaries for endpoints.
- Validate Against the Spec: Use tools that lint and validate your OpenAPI file to ensure accuracy.
Conclusion
Documenting your API with Swagger/OpenAPI ensures developers can easily explore and test your endpoints. We covered implementations in ASP.NET, Spring Boot, Express.js, Next.js, Flask, and Laravel. Regardless of the platform, Swagger acts as a consistent, interactive, and developer-friendly way to share how your API works.
✅ Key takeaways:
- Swagger/OpenAPI is language-agnostic and widely supported.
- Interactive docs boost adoption and reduce onboarding time.
- Each framework has simple packages/libraries to enable docs.
- Postman is complementary to Swagger for testing workflows.
- Best practices ensure your documentation remains secure and useful.
- API documentation should always evolve alongside your API.