0
0
FastAPIframework~5 mins

OpenAPI schema customization in FastAPI

Choose your learning style9 modes available
Introduction

OpenAPI schema customization lets you change how your API's description looks. This helps make your API easier to understand and use.

You want to add a title, version, or description to your API docs.
You need to add extra information like contact or license details.
You want to change the default URL where the docs appear.
You want to hide some endpoints from the docs.
You want to add tags or group endpoints for clarity.
Syntax
FastAPI
from fastapi import FastAPI

app = FastAPI(
    title="My API",
    description="This API does cool things.",
    version="1.0.0",
    contact={"name": "Support", "email": "support@example.com"},
    license_info={"name": "MIT"},
    openapi_url="/custom_openapi.json",
    docs_url="/custom_docs"
)

You customize the schema by passing parameters when creating the FastAPI app.

openapi_url changes the JSON schema URL; docs_url changes the interactive docs URL.

Examples
Simple title and version change for your API docs.
FastAPI
app = FastAPI(title="Book Store API", version="2.0")
Adds a description and contact info to the docs.
FastAPI
app = FastAPI(
    description="API for managing tasks.",
    contact={"name": "Jane Doe", "email": "jane@example.com"}
)
Changes where the OpenAPI JSON and docs are served.
FastAPI
app = FastAPI(
    openapi_url="/api/schema.json",
    docs_url="/api/docs"
)
Sample Program

This example shows how to set title, description, version, contact, and license info. It also changes the OpenAPI and docs URLs. The endpoint '/hello' appears in docs with a tag. The '/hidden' endpoint is not shown in the docs.

FastAPI
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI(
    title="Simple API",
    description="This API shows how to customize OpenAPI schema.",
    version="0.1",
    contact={"name": "API Support", "email": "support@simpleapi.com"},
    license_info={"name": "Apache 2.0"},
    openapi_url="/openapi.json",
    docs_url="/docs"
)

@app.get("/hello", tags=["Greetings"])
async def say_hello():
    return {"message": "Hello, world!"}

@app.get("/hidden", include_in_schema=False)
async def hidden_endpoint():
    return JSONResponse({"secret": "This is hidden from docs"})
OutputSuccess
Important Notes

Use include_in_schema=False to hide endpoints from docs.

Tags help organize endpoints in the docs.

Changing openapi_url and docs_url helps if you want custom paths for your API docs.

Summary

Customize your API docs by setting parameters in FastAPI app creation.

You can add info like title, version, description, contact, and license.

You can hide endpoints or change where docs appear.