Generate an OpenAPI Spec from Mock Routes in Python
This Python script generates an OpenAPI 3.0 specification from a simple mock routes dictionary, mapping each HTTP method to response examples.
Python code
42 linesimport json
from pathlib import Path
def generate_openapi_spec(routes: dict, title: str = "Mock API", version: str = "1.0.0") -> dict:
paths = {}
for route, methods in routes.items():
path_item = {}
for method, response_data in methods.items():
method = method.lower()
if method not in {"get", "post", "put", "delete", "patch"}:
continue
path_item[method] = {
"summary": f"{method.upper()} {route}",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"example": response_data
}
}
}
}
}
if path_item:
paths[route] = path_item
return {
"openapi": "3.0.0",
"info": {"title": title, "version": version},
"paths": paths
}
if __name__ == "__main__":
mock_routes = {
"/users": {"GET": [{"id": 1, "name": "Alice"}], "POST": {"id": 2, "name": "Bob"}},
"/health": {"GET": {"status": "ok"}}
}
spec = generate_openapi_spec(mock_routes)
print(json.dumps(spec, indent=2))
Output
{
"openapi": "3.0.0",
"info": {
"title": "Mock API",
"version": "1.0.0"
},
"paths": {
"/users": {
"get": {
"summary": "GET /users",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"example": [
{
"id": 1,
"name": "Alice"
}
]
}
}
}
}
},
"post": {
"summary": "POST /users",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"example": {
"id": 2,
"name": "Bob"
}
}
}
}
}
}
},
"/health": {
"get": {
"summary": "GET /health",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"example": {
"status": "ok"
}
}
}
}
}
}
}
}
}
How it works
The function iterates over a dictionary where keys are route paths and values are dictionaries mapping HTTP methods to example response data. It normalizes method names to lowercase and only includes recognized HTTP verbs (GET, POST, PUT, DELETE, PATCH). Each method is turned into an OpenAPI operation object with a summary and a 200 response containing the example payload under application/json. This approach provides a minimal but valid OpenAPI 3.0 specification that can be used to document mock endpoints for frontend development or testing. The script prints the spec as formatted JSON for easy inspection.
Common mistakes
- Forgetting that OpenAPI requires lowercase HTTP method keys in the paths object
- Assuming all route definitions include every HTTP method, causing missing operations
- Not filtering out unsupported HTTP methods, leading to invalid spec entries
- Confusing the example data structure with the OpenAPI schema definition
Variations
- Use `yaml.safe_dump` to output the spec in YAML format instead of JSON
- Enrich the spec with request bodies, parameters, and response schemas for more accurate documentation
Real-world use cases
- Generating quick API documentation for a prototype or mock server that frontend teams can reference while the real backend is built.
- Automating the creation of OpenAPI specs for route stubs in test environments so API consumers can generate client SDKs early.
- Producing a baseline OpenAPI contract for a legacy system by introspecting mock route definitions before full schema extraction.
Sponsored
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- How to Add HATEOAS Links to a Python API Response easy
Keep learning
Related tutorials and quizzes for this topic.