Skip to content
Skills Library
Programming · Building & coding

fastapi

/fastapi

Use when building APIs with FastAPI. Covers dependency injection, Pydantic v2 validation, async database access, authentication, background tasks, and testing. Trigger on "fastapi endpoint is slow under load", "set up depends for the db session", "pydantic v2 validation error", "test my fastapi app". Do not use for API contract decisions like pagination or versioning — see the api-design skill.

Licence
MIT
Last repository change
24.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
1
Deprecation

No signals detected. Repository changed on 24.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Use when building APIs with FastAPI. Covers dependency injection, Pydantic v2 validation, async database access, authentication, background tasks, and testing. Trigger on "fastapi endpoint is slow under load", "set up depends for the db session", "pydantic v2 validation error", "test my fastapi app". Do not use for API contract decisions like pagination or versioning — see the api-design skill.

Triggers from the description

fastapi endpoint is slow under loadset up depends for the db sessionpydantic v2 validation errortest my fastapi app
Original author description

Use when building APIs with FastAPI. Covers dependency injection, Pydantic v2 validation, async database access, authentication, background tasks, and testing. Trigger on "fastapi endpoint is slow under load", "set up depends for the db session", "pydantic v2 validation error", "test my fastapi app". Do not use for API contract decisions like pagination or versioning — see the api-design skill.

How it works

  1. Purpose
  2. When to Use
  3. Capabilities
  4. Inputs
  5. Outputs
  6. Workflow
  7. Best Practices
  8. Examples
  9. Notes
Original SKILL.md headings · 94 lines, 571 words
SKILL.md preview
---
name: fastapi
description: Use when building APIs with FastAPI. Covers dependency injection, Pydantic v2 validation, async database access, authentication, background tasks, and testing. Trigger on "fastapi endpoint is slow under load", "set up depends for the db session", "pydantic v2 validation error", "test my fastapi app". Do not use for API contract decisions like pagination or versioning — see the api-design skill.
metadata:
  category: backend
  version: 1.0.0
  tags: [fastapi, python, pydantic, async, api]
---

# FastAPI

## Purpose

Build FastAPI services that use the framework's strengths — declarative validation and dependency injection — without falling into its two standard traps: blocking calls inside `async def`, and business logic in the route handler.

## When to Use

- Building or reviewing a FastAPI application.
- Structuring dependencies, authentication, and database sessions.
- Diagnosing latency that appears only under concurrency.
- Writing tests for FastAPI endpoints.

## Capabilities

- Route and router organization.
- Pydantic v2 models for request, response, and settings.
- Dependency injection with scoped lifecycles.
- Async SQLAlchemy sessions, correctly scoped per request.
- Authentication and authorization dependencies.
- Testing with `httpx.AsyncClient` and dependency overrides.

## Inputs

- The API contract and the data layer.
- Whether the workload is I/O-bound (nearly always) or CPU-bound.

## Outputs

- Thin route handlers delegating to service functions.
- Response models that control exactly what is serialized.
- A test suite that overrides dependencies rather than mocking internals.

## Workflow

1. **Define the schemas** — Separate request, response, and internal models. Never return an ORM object directly; a `response_model` is your defense against leaking a password hash.
2. **Build the dependencies** — Database session, current user, feature flags. These are the injection points that make the app testable.
3. **Keep handlers thin** — Parse, authorize, delegate, return. Business logic lives in a service module that knows nothing about HTTP.
4. **Get async right** — In an `async def` handler, every I/O call must be awaited. A blocking call there stalls the entire event loop, not just that request.
5. **Test through the app** — `httpx.AsyncClient` with `app.dependency_overrides` gives you real routing, real validation, and a fake database.

## Best Practices

- A blocking call inside `async def` (a sync DB driver, `requests`, `time.sleep`) blocks every concurrent request on that worker. If a handler must call blocking code, define it as `def` — FastAPI runs it in a thread pool.
- Always set `response_model`. Without it, whatever your service returns is what the client sees, including fields you added last week.
- Use `Annotated[Session, Depends(get_session)]` — it keeps signatures readable and reusable.
- Validate settings with `pydantic-settings` at startup. Fail to boot on a bad config rather than at 3am on the first request that touches it.
- `BackgroundTasks` runs in the same process and dies with it. For anything that must not be lost, use a real queue.
- Mount routers by domain, not by HTTP verb.

## Examples

**Dependency-injected handler and an overridable test:**

```python
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status

router = APIRouter(prefix="/orders", tags=["orders"])

SessionDep = Annotated[AsyncSession, Depends(get_session)]
CurrentUser = Annotated[User, Depends(get_current_user)]


@router.post("", response_model=OrderRead, status_code=status.HTTP_201_CREATED)
async def create_order(
    payload: OrderCreate,
    session: SessionDep,
    user: CurrentUser,
) -> Order:
    try:
        return await orders.place(session, customer_id=user.id, items=payload.items)
    except InsufficientInventory as e:
        raise HTTPException(status.HTTP_409_CONFLICT, detail=str(e)) from e
```

```python
@pytest.fixture
async def client(session: AsyncSession) -> AsyncIterator[AsyncClient]:
    app.dependency_overrides[get_session] = lambda: session
    app.dependency_overrides[get_current_user] = lambda: User(id="usr_test")
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as c:
        yield c
    app.dependency_overrides.clear()
```

## Notes

- Pydantic v2 is roughly an order of magnitude faster than v1 on validation, but `Config` classes, validators, and `.dict()` all changed. Do not mix idioms.
- `@lru_cache` on a settings factory is the standard way to make configuration a singleton dependency.
- FastAPI's generated OpenAPI schema is only as good as your response models and status codes. Treat the generated docs as a review artifact.

Versions

RepositoryScoreLicence
This page · nimadorostkar/Claude-Skills-collection100MIT
ericrisco/rsc-harness100MIT
TerminalSkills/skills100Apache-2.0
itechmeat/llm-code100MIT
fastapi/fastapi100MIT
claude-dev-suite/claude-dev-suite100MIT
lynricsy/hyperskills100MIT
G1Joshi/Agent-Skills100MIT
chrishuffman5/domain-expert100MIT

Database snapshot: 13.11.2026 · package version cbfacaf9f81e (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 95fastapi-patterns
    FastAPI best practices covering project structure, Pydantic v2 schemas, dependency injection, async handlers, authentication, authorization, transactional service layers, and testing with httpx and pytest. Use when building or reviewing FastAPI apps — Pydantic schemas,…
  • 100python-fastapi-pydantic
    Use this skill when building high-performance, asynchronous REST APIs in Python using FastAPI, Pydantic validation, and OpenAPI.
  • 95fastapi-validation
    Use when FastAPI validation with Pydantic models. Use when building type-safe APIs with robust request/response validation.
  • 100fastapi-developer
    Use when building modern async Python APIs with FastAPI, implementing Pydantic v2 validation, dependency injection patterns, or deploying high-performance ASGI applications.
  • 100fastapi-patterns
    Build production FastAPI applications with dependency injection, middleware, background tasks, and structured project layouts. Covers async patterns, Pydantic models, OpenAPI customization, and testing strategies. Triggers on FastAPI development, Python API, or async web framework requests.
  • 95fastapi-patterns
    FastAPI best practices covering project structure, Pydantic v2 schemas, dependency injection, async handlers, authentication, authorization, transactional service layers, and testing with httpx and pytest. Use when building or reviewing FastAPI apps — Pydantic schemas,…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.