fastapi-rest-api

verified

9ce4995a-ed8a-4dd2-8035-749c518002ba

Build a FastAPI REST API — routers, Pydantic models, dependency injection, error handling, and testing.

Metadata

Skill ID
9ce4995a-ed8a-4dd2-8035-749c518002ba
Version
1
Owner
global
Tags
fastapipythonrestapibackend
Signature
verified
Integrity
OK
Content hash
922c341e264f2ce181e36495e57da9c69ebe71129aa1cbd7df3af9b27f37b1f1
Created
2026-08-05T18:29:00Z

Skill file

Raw skill file (markdown source)
# Building a FastAPI REST API

Use when exposing an HTTP API: resources, validation, OpenAPI docs, and clean error
responses.

## Structure

```
app/
  main.py        # FastAPI() + include_router
  routers/
    skills.py    # APIRouter
  schemas.py     # Pydantic request/response models
```

```python
from fastapi import APIRouter

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


@router.get("/{skill_id}")
def get_skill(skill_id: str) -> dict: ...
```

## Dependency injection

Resolve auth/db via `Depends` so handlers stay thin and testable:

```python
def get_db():
    yield conn


@router.get("/{id}")
def read(db=Depends(get_db)): ...
```

## Error handling

Raise `HTTPException(status_code=404, detail="...")`, or map domain exceptions
to status codes in a small handler so handlers never leak internals.

## Testing

```python
from fastapi.testclient import TestClient


def test_create():
    client = TestClient(app)
    r = client.post("/skills", json={...})
    assert r.status_code == 201
```

## Pitfalls

- Declare response models to get typed OpenAPI and docs.
- Use `Depends` for shared setup instead of globals — it enables override in tests.
- Don't put business logic in routers; keep them as thin transport layer.

Attached files