How to Define an OpenAPI Schema with FastAPI

Joël-Steve N.
3 min readJan 26, 2024

--

OpenAPI is a specification that describes RESTful APIs using a standardized format. It allows developers to define the structure, endpoints, parameters, and responses of an API. FastAPI, a modern web framework for building APIs with Python, provides built-in support for generating OpenAPI schemas. In this blog post, we will guide you through the process of defining an OpenAPI schema using FastAPI.

What is OpenAPI?

OpenAPI, formerly known as Swagger, is a specification that provides a machine-readable format for describing and documenting RESTful APIs. It uses a JSON or YAML format to define the endpoints, methods, parameters, request/response bodies, and other details of an API. OpenAPI allows developers to design and document APIs in a consistent and standardized way, making it easier for clients to understand and interact with the API.

FastAPI and OpenAPI

FastAPI simplifies the process of defining an OpenAPI schema by automatically generating it based on your API code. FastAPI leverages the power of Pydantic models and type annotations to create an accurate and detailed OpenAPI schema. By using FastAPI, you can focus on building your API functionality while letting it handle the OpenAPI generation for you.

Defining an OpenAPI Schema with FastAPI

To define an OpenAPI schema using FastAPI, complete the following steps:

Step 1: Import Dependencies

Start by importing the necessary dependencies in your Python file (main.py):

from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi

Step 2: Create a FastAPI App

Create a FastAPI application instance:

app = FastAPI()

Step 3: Define API Routes

Define your API routes using FastAPI’s decorators. Here’s an example of a route that retrieves a user by its ID:

@app.get("/users/{user_id}")
def get_user(user_id: int):
"""
Retrieve user information by ID.
"""
# ...
return {"user_id": user_id, "name": "John Doe"}

Step 4: Generate OpenAPI Schema

Add a function that generates the OpenAPI schema based on your FastAPI application:

def generate_openapi_schema():
"""
Generate the OpenAPI schema for the FastAPI application.
"""
return get_openapi(
title="My API",
version="1.0.0",
description="This is my API description",
routes=app.routes,
)

Step 5: Expose OpenAPI Endpoint

Create another route that exposes the generated OpenAPI schema:

@app.get("/openapi.json")
def get_openapi_endpoint():
"""
Retrieve the generated OpenAPI schema.
"""
return JSONResponse(content=generate_openapi_schema())

Make sure to import JSONResponse from fastapi.responses at the beginning of your file.

Step 6: Run the App

from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse
import uvicorn

app = FastAPI()

def generate_openapi_schema():
"""
Generate the OpenAPI schema for the FastAPI application.
"""
return get_openapi(
title="My API",
version="1.0.0",
description="This is my API description",
routes=app.routes,
)

@app.get("/users/{user_id}")
def get_user(user_id: int):
"""
Retrieve user information by ID.
"""
# ...
return {"user_id": user_id, "name": "John Doe"}

@app.get("/openapi.json")
def get_openapi_endpoint():
"""
Retrieve the generated OpenAPI schema.
"""
return JSONResponse(content=generate_openapi_schema())

if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8200)

Finally, run your FastAPI application using Uvicorn or any other ASGI server of your choice:

python main.py

or

uvicorn main:app --host 127.0.0.1 --port 8200

Testing the OpenAPI Schema

To test the generated OpenAPI schema, start the FastAPI application and navigate to the /openapi.json endpoint in your browser. You will see the generated OpenAPI schema in JSON format, describing your API endpoints, parameters, and responses.

Conclusion

FastAPI simplifies the process of defining an OpenAPI schema by automatically generating it based on your API code. By leveraging the power of Pydantic models and type annotations, FastAPI ensures that your schema is accurate, consistent, and up-to-date. In this blog post, we walked you through the process of defining an OpenAPI schema with FastAPI. Now you can start building powerful and well-documented APIs with ease.

--

--

Joël-Steve N.
Joël-Steve N.

Written by Joël-Steve N.

Senior Back-End Developer (Python, JavaScript, Java) | Community Manager & Tech Leader

No responses yet