Skip to main content
skill CX Codex

fastapi-expert · personamanagmentlayer — Claude Code skill: what it does, how to install

fastapi-expert — a skill for building FastAPI APIs: Pydantic models, JWT auth, SQLAlchemy integration and background tasks, all with working code patterns.

Apache-2.0 218 installs ★ 45 updated 2026-10-12

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add personamanagmentlayer/pcl --skill fastapi-expert -a claude-code
Open on GitHub

What fastapi-expert does

The skill packages reference patterns for FastAPI work: a base app with routes and Pydantic models, dependency injection for database sessions and auth, JWT tokens via jose, and password hashing via passlib. It also covers SQLAlchemy wiring with AsyncSession and CRUD helpers, request validation through Pydantic validators, and BackgroundTasks for deferred work like sending an email after a request.

It triggers when a task mentions Python, API, async, REST, OpenAPI or Pydantic. The code assumes an async stack: SQLAlchemy's AsyncSession, asyncpg for PostgreSQL, and uvicorn as the server. Running any of it requires Python and those libraries installed separately — the skill shows the patterns, it doesn't install anything.

What it helps with

  • scaffold CRUD routes with Pydantic request and response models
  • wire up JWT login with password hashing
  • connect SQLAlchemy through an async session
  • move token checks and database access into FastAPI dependencies
  • trigger a background email send after a request completes

Example prompts for the agent

  • Write a /users route with UserCreate and UserResponse Pydantic models
  • Add JWT login using OAuth2PasswordBearer and a get_current_user dependency
  • Set up an async PostgreSQL connection for FastAPI through SQLAlchemy

How to install fastapi-expert

1Skills CLI (Vercel)

npx skills add personamanagmentlayer/pcl --skill fastapi-expert -a claude-code

2Manually: put the files in place

~/.claude/skills/fastapi-expert/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/fastapi-expert/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about fastapi-expert

How do I install fastapi-expert in Claude Code?

Run npx skills add personamanagmentlayer/pcl --skill fastapi-expert -a claude-code; the skill lands at ~/.claude/skills/fastapi-expert/SKILL.md.

What does the fastapi-expert skill do?

It provides code patterns for FastAPI apps: Pydantic-based routes, JWT authentication, SQLAlchemy setup and background tasks. It activates on mentions of Python, API, async, REST, OpenAPI or Pydantic.

What stack do the fastapi-expert examples assume?

An async one: SQLAlchemy's AsyncSession, asyncpg for PostgreSQL, jose for JWT, passlib for password hashing, and uvicorn to run the server.

Source text

SKILL.md · Apache-2.0
---
name: fastapi-expert
version: 1.1.0
description: >-
  Expert-level FastAPI development for high-performance Python APIs with async support. Use
  when the user mentions Python, API, async, REST, OpenAPI, or Pydantic, or when the task
  involves FastAPI Features.
category: api
tags: [fastapi, python, api, async, rest, openapi, pydantic]
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash(python:*, pip:*, uvicorn:*)
---

# FastAPI Expert

Expert guidance for FastAPI - modern, fast Python web framework for building APIs with automatic OpenAPI documentation and type safety.

## Core Concepts

### FastAPI Features

- Fast performance (Starlette + Pydantic)
- Automatic OpenAPI/Swagger docs
- Type hints and validation
- Async/await support
- Dependency injection
- OAuth2 and JWT
- WebSocket support

### Key Components

- Path operations (routes)
- Request/response models (Pydantic)
- Dependency injection
- Middleware
- Background tasks
- Testing with TestClient

## Basic FastAPI Application

```python
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, EmailStr, Field
from typing import List, Optional
import uvicorn

app = FastAPI(
    title="My API",
    description="Production-ready FastAPI",
    version="1.0.0"
)

# Models
class UserCreate(BaseModel):
    email: EmailStr
    name: str = Field(..., min_length=2, max_length=100)
    age: Optional[int] = Field(None, ge=0, le=150)

class UserResponse(BaseModel):
    id: int
    email: str
    name: str

    class Config:
        from_attributes = True

# Routes
@app.post("/users", response_model=UserResponse, status_code=201)
async def create_user(user: UserCreate):
    # Create user in database
    db_user = await db.users.create(**user.dict())
    return db_user

@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
    user = await db.users.get(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user

@app.get("/users", response_model=List[UserResponse])
async def list_users(skip: int = 0, limit: int = 100):
    return await db.users.find_many(skip=skip, limit=limit)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

## Dependency Injection

```python
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession

# Database dependency
async def get_db() -> AsyncSession:
    async with async_session() as session:
        yield session

# Auth dependency
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: AsyncSession = Depends(get_db)
):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials"
    )

    payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    user_id: int = payload.get("sub")
    if user_id is None:
        raise credentials_exception

    user = await db.get(User, user_id)
    if user is None:
        raise credentials_exception

    return user

# Use dependencies
@app.get("/me", response_model=UserResponse)
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user

@app.post("/posts")
async def create_post(
    post: PostCreate,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    db_post = Post(**post.dict(), user_id=current_user.id)
    db.add(db_post)
    await db.commit()
    return db_post
```

## Authentication

```python
from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)

def create_access_token(data: dict, expires_delta: timedelta = None):
    to_encode = data.copy()
    expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

@app.post("/token")
async def login(
    form_data: OAuth2PasswordRequestForm = Depends(),
    db: AsyncSession = Depends(get_db)
):
    user = await authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid credentials")

    access_token = create_access_token(data={"sub": str(user.id)})
    return {"access_token": access_token, "token_type": "bearer"}
```

## Database Integration (SQLAlchemy)

```python
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy import Column, Integer, String, Boolean

DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname"

engine = create_async_engine(DATABASE_URL, echo=True)
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

Base = declarative_base()

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True, nullable=False)
    hashed_password = Column(String, nullable=False)
    is_active = Column(Boolean, default=True)

# CRUD operations
async def get_user(db: AsyncSession, user_id: int):
    return await db.get(User, user_id)

async def create_user(db: AsyncSession, user: UserCreate):
    hashed_password = get_password_hash(user.password)
    db_user = User(email=user.email, hashed_password=hashed_password)
    db.add(db_user)
    await db.commit()
    await db.refresh(db_user)
    return db_user
```

## Request Validation

```python
from pydantic import BaseModel, validator, root_validator
from typing import Optional
from datetime import date

class PostCreate(BaseModel):
    title: str = Field(..., min_length=5, max_length=200)
    content: str = Field(..., min_length=10)
    published: bool = False
    tags: List[str] = Field(default_factory=list, max_items=10)

    @validator('tags')
    def validate_tags(cls, v):
        return [tag.lower().strip() for tag in v]

    @validator('title')
    def validate_title(cls, v):
        if any(word in v.lower() for word in ['spam', 'xxx']):
            raise ValueError('Invalid content')
        return v
```

## Background Tasks

```python
from fastapi import BackgroundTasks

def send_email(email: str, message: str):
    # Send email
    print(f"Sending email to {email}: {message}")

@app.post("/send-notification")
async def send_notification(
    email: str,
    background_tasks: BackgroundTasks
):
    background_tasks.add_task(send_email, email, "Welcome!")
    return {"message": "Notification sent"}
```

## Testing

```python
from fastapi.testclient import TestClient
import pytest

client = TestClient(app)

def test_create_user():
    response = client.post(
        "/users",
        json={"email": "[email protected]", "name": "Test User"}
    )
    assert response.status_code == 201
    assert response.json()["email"] == "[email protected]"

def test_get_user():
    response = client.get("/users/1")
    assert response.status_code == 200
    assert "email" in response.json()

@pytest.mark.asyncio
async def test_async_endpoint():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/users")
    assert response.status_code == 200
```

## Best Practices

- Use Pydantic models for validation
- Implement proper error handling
- Use dependency injection
- Add rate limiting
- Enable CORS properly
- Use async/await for I/O
- Document with docstrings
- Add proper logging

## Resources

- FastAPI Docs: https://fastapi.tiangolo.com/
- Pydantic: https://docs.pydantic.dev/
- Starlette: https://www.starlette.io/

© personamanagmentlayer · Apache-2.0 · personamanagmentlayer/pcl

Similar skills

All skills for Backend and APIs →

fastapi-expert by other authors comes first.

fastapi-expert https://github.com/Jeffallan fastapi-expert guides async FastAPI development with Pydantic V2, from REST routes and authentication to database operations and tests. CX Codex +1 6,600installs fastapi-expert martinholovsky fastapi-expert guides coding agents to build async FastAPI applications with Pydantic v2, SQLAlchemy 2.0, OAuth2 authentication, and pytest test suites. CX Codex +1 267installs fastapi-python Mindrally fastapi-python — a skill for Claude Code, Codex, Cursor and other platforms: FastAPI expert with async Python patterns. Activates when building REST APIs, validating with Pydantic or optimizing performance. CX Codex +1 14,100installs FastAPI pluginagentmarketplace A FastAPI skill for your coding agent: routes, Pydantic models, async handlers, auth and tests. Useful when you are building a Python API. CX Codex +1 181installs fastapi-microservices-development manutej fastapi-microservices-development is a Claude Code skill for structuring Python microservices with FastAPI, dependency injection, async routes, and service-to-service communication. CX Codex +1 591installs FastAPI Customer Support Tech Enablement manutej FastAPI Customer Support Tech Enablement guides agents in building customer support APIs with FastAPI, covering ticket workflows and operator authentication. CX Codex +1 424installs openapi-to-application-python-fastapi official Awesome Copilot Community The openapi-to-application-python-fastapi plugin generates FastAPI applications from OpenAPI specs, including project scaffolding, routes, and dependency injection. Use it for async Python APIs. ★ 41,430repo stars fastapi-endpoint davila7 Guides you through planning and coding async FastAPI endpoints with Pydantic v2 schemas, SQLAlchemy 2.0, auth checks, and pytest suites. Gathers requirements before writing code. CX Codex +1 393installs

From the same set104

The whole set →
flask-expert flask-expert guides Python work with Flask apps, REST APIs, extensions, and deployment. Use it when a task involves Jinja2, Flask structure, authentication, or API design. CX Codex +1 225installs csharp-expert The csharp-expert skill guides agents through modern C# work with .NET, ASP.NET Core, LINQ, and async code. Use it for backend services and enterprise application patterns. CX Codex +1 221installs maritime-expert The maritime-expert skill gives an agent maritime domain knowledge for vessel tracking, port operations, cargo systems, and shipping software. CX Codex +1 221installs kafka-expert kafka-expert — a skill for Apache Kafka work: producer and consumer patterns, Kafka Streams topologies, partitioning and consumer groups, ready whenever a project touches event streaming. CX Codex +1 220installs nodejs-expert nodejs-expert guides the AI assistant in backend development with Node.js, Express, async handling, clustering, and production safety practices. CX Codex +1 216installs databricks-expert databricks-expert hands the agent Databricks practice for clusters, Delta Lake, PySpark and MLflow. Useful when a pipeline crawls or a join falls apart. CX Codex +1 215installs kubernetes-expert kubernetes-expert guides cluster operations, deployment manifests, network debugging, and Helm chart setups. Useful for DevOps engineers and container deployments. CX Codex +1 215installs spring-boot-expert spring-boot-expert guides coding agents through Spring Boot development, REST API design, and microservice setup in Java projects. CX Codex +1 212installs

Project sponsors

Companies that keep this analytics open