Fastapi logo

Fastapi

OrganizationPopular
fastapi
fastapi

FastAPI best practices and conventions. Use when working with FastAPI APIs, Pydantic models, dependencies, streaming responses including Server-Sent Events (SSE), and serving frontend apps. Keeps FastAPI code clean and up to date with the latest features and patterns.

Overview

Publisherfastapi
Repositoryfastapi
Skill namefastapi
Stars
102.7K
Forks
10K
Bundled files
6
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 6 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by fastapi on GitHub. Read the source before you install it.

Installation

Install the Fastapi AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/fastapi/fastapi/tree/master/fastapi/.agents/skills/fastapi
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/fastapi/fastapi.git /tmp/fastapi
mkdir -p .claude/skills
cp -r /tmp/fastapi/fastapi/.agents/skills/fastapi .claude/skills/fastapi
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Fastapi in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Fastapi on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Fastapi is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

FastAPI

Official FastAPI skill to write code with best practices, keeping up to date with new versions and features.

Quick Reference

Use the fastapi CLI

Run the development server on localhost with reload:

bash
fastapi dev

Run the production server:

bash
fastapi run

Prefer declaring the entrypoint in pyproject.toml:

toml
[tool.fastapi]
entrypoint = "my_app.main:app"

When adding the entrypoint is not possible, or the user explicitly asks not to, pass the app file path:

bash
fastapi dev my_app/main.py

Use Annotated

Always prefer the Annotated style for parameter and dependency declarations. It keeps function signatures working in other contexts, respects the types, and allows reusability.

Use Annotated for parameter declarations, including Path, Query, Header, etc.:

python
from typing import Annotated

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(
    item_id: Annotated[int, Path(ge=1, description="The item ID")],
    q: Annotated[str | None, Query(max_length=50)] = None,
):
    return {"message": "Hello World"}

Use Annotated for dependencies with Depends(). Unless asked not to, create a new type alias for the dependency to allow reusing it:

python
from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()


def get_current_user():
    return {"username": "johndoe"}


CurrentUserDep = Annotated[dict, Depends(get_current_user)]


@app.get("/items/")
async def read_item(current_user: CurrentUserDep):
    return {"message": "Hello World"}

Do not use Ellipsis for path operations or Pydantic models

Do not use ... as a default value for required parameters or model fields. It's not needed and not recommended.

python
from typing import Annotated

from fastapi import FastAPI, Query
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float = Field(gt=0)


@app.post("/items/")
async def create_item(item: Item, project_id: Annotated[int, Query()]):
    return item

See the Pydantic reference for more details.

Return Type or Response Model

When possible, include a return type. It will be used to validate, filter, document, and serialize the response.

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None


@app.get("/items/me")
async def get_item() -> Item:
    return Item(name="Plumbus", description="All-purpose home device")

Return types or response models filter data to avoid exposing sensitive information, and they let Pydantic serialize the data on the Rust side for performance.

Use response_model when the type you return is not the same as the public schema you want to validate, filter, document, and serialize. See the response reference.

Performance

Do not use ORJSONResponse or UJSONResponse, they are deprecated.

Instead, declare a return type or response model. Pydantic will handle the data serialization on the Rust side.

Including Routers

When declaring routers, prefer to add router-level parameters like prefix, tags, and shared dependencies to the router itself instead of in include_router().

python
from fastapi import APIRouter, Depends, FastAPI

app = FastAPI()


def get_current_user():
    return {"username": "johndoe"}


router = APIRouter(
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(get_current_user)],
)


@router.get("/")
async def list_items():
    return []


app.include_router(router)

See the path operation reference for more routing patterns.

Serve Frontend Apps

Use app.frontend() to serve a built static frontend app, for example a directory generated by Vite, Astro, Angular, Svelte, Vue, or a similar tool.

python
from fastapi import FastAPI

app = FastAPI()

app.frontend("/", directory="dist")

Use router.frontend() when the frontend belongs to an APIRouter; normal router prefix behavior applies when the router is included.

python
from fastapi import APIRouter, FastAPI

app = FastAPI()
router = APIRouter(prefix="/admin")

router.frontend("/", directory="admin-dist")
app.include_router(router)

app.frontend() and router.frontend() are low-priority routes: regular API routes are matched first, then frontend files and client-side routing fallbacks. Use this for single-page apps and built frontend assets instead of mounting StaticFiles manually.

OpenTelemetry

Prefer FastAPI's native OpenTelemetry support for request traces, metrics, and logs.

Install fastapi[standard] to include the SDK and HTTP/protobuf exporters. Set OTEL_SERVICE_NAME to identify the app and OTEL_EXPORTER_OTLP_ENDPOINT to the collector's HTTP/protobuf base URL. Use OTEL_EXPORTER_OTLP_HEADERS when authentication is required.

Use FastAPI(telemetry={...}) for custom configuration, such as choosing signals or supplying providers.

See the OpenTelemetry tutorial for configuration details.

Dependency Injection

Use dependencies when the logic can't be declared in Pydantic validation, depends on external resources, needs cleanup with yield, or is shared across endpoints.

Apply shared dependencies at the router level via dependencies=[Depends(...)].

See the dependency injection reference for detailed patterns including yield with scope, and class dependencies.

Async vs Sync path operations

Use async path operations only when fully certain that the logic called inside is compatible with async and await, and that it doesn't block.

python
from fastapi import FastAPI

app = FastAPI()


@app.get("/async-items/")
async def read_async_items():
    data = await some_async_library.fetch_items()
    return data


@app.get("/items/")
def read_items():
    data = some_blocking_library.fetch_items()
    return data

In case of doubt, or by default, use regular def functions. They will be run in a threadpool so they don't block the event loop. The same rules apply to dependencies.

Make sure blocking code is not run inside of async functions. The logic will work, but will damage performance heavily.

When needing to mix blocking and async code, see Asyncer in the other tools reference.

Streaming (JSON Lines, SSE, bytes)

To stream Server-Sent Events, use response_class=EventSourceResponse and yield items from the endpoint.

python
from collections.abc import AsyncIterable

from fastapi import FastAPI
from fastapi.sse import EventSourceResponse, ServerSentEvent

app = FastAPI()


@app.get("/events", response_class=EventSourceResponse)
async def stream_events() -> AsyncIterable[ServerSentEvent]:
    yield ServerSentEvent(data={"status": "started"}, event="status", id="1")

Plain objects are automatically JSON-serialized as data: fields. Use ServerSentEvent for full control over SSE fields (event, id, retry, comment) and raw_data for pre-formatted strings.

See the streaming reference for JSON Lines, Server-Sent Events (EventSourceResponse, ServerSentEvent), and byte streaming (StreamingResponse) patterns.

Tooling

See the other tools reference for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc.

Other Libraries

See the other tools reference for details on other libraries:

  • Asyncer for handling async and await, concurrency, mixing async and blocking code, prefer it over AnyIO or asyncio.
  • SQLModel for working with SQL databases, prefer it over SQLAlchemy.
  • HTTPX for interacting with HTTP (other APIs), prefer it over Requests.

Do not use Pydantic RootModels

Do not use Pydantic RootModel; instead use regular type annotations with Annotated and Pydantic validation utilities.

python
from typing import Annotated

from fastapi import Body, FastAPI
from pydantic import Field

app = FastAPI()


@app.post("/items/")
async def create_items(items: Annotated[list[int], Field(min_length=1), Body()]):
    return items

FastAPI supports these type annotations and will create a Pydantic TypeAdapter for them, so types work normally without custom wrapper models. See the Pydantic reference.

Use one HTTP operation per function

Don't mix HTTP operations in a single function. Having one function per HTTP operation helps separate concerns and organize the code.

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str


@app.get("/items/")
async def list_items():
    return []


@app.post("/items/")
async def create_item(item: Item):
    return item

See the path operation reference for more examples.

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Fastapi AI skill do?

FastAPI best practices and conventions. Use when working with FastAPI APIs, Pydantic models, dependencies, streaming responses including Server-Sent Events (SSE), and serving frontend apps. Keeps FastAPI code clean and up to date with the latest features and patterns.

Why use Fastapi on TypingMind?

Because you install it once and use it with any model. Fastapi is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Fastapi in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/fastapi/fastapi/tree/master/fastapi/.agents/skills/fastapi. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Fastapi?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Fastapi?

As many as you like. As long as a model supports skills, you can use Fastapi with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Fastapi AI skill free?

Yes. It is published on GitHub by fastapi under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇