All skills
jeffallan avatar

/fastapi-expert

@efebc44
by jeffallanjeffallan/claude-skills12k stars
1,124

Use when building high-performance async Python APIs with FastAPI and Pydantic V2. Invoke to create REST endpoints, define Pydantic models, implement authentication flows, set up async SQLAlchemy database operations, add JWT authentication, build WebSocket endpoints, or generate OpenAPI documentation. Trigger terms: FastAPI, Pydantic, async Python, Python API, REST API Python, SQLAlchemy async, JWT authentication, OpenAPI, Swagger Python.

Use this Skill: https://skilld.dev/gh/jeffallan/claude-skills/fastapi-expert

This session only. Nothing lands on disk.

referencestesting-async.md

≈1.1k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Async Testing

Test Setup

import pytest
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker

from app.main import app
from app.core.deps import get_db
from app.models import Base

# Test database
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"
test_engine = create_async_engine(TEST_DATABASE_URL, echo=True)
test_session = async_sessionmaker(test_engine, expire_on_commit=False)

@pytest.fixture(scope="session")
def anyio_backend():
    return "asyncio"

@pytest.fixture(scope="function")
async def db():
    async with test_engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    async with test_session() as session:
        yield session
    async with test_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)

@pytest.fixture
async def client(db: AsyncSession):
    def override_get_db():
        return db

    app.dependency_overrides[get_db] = override_get_db
    async with AsyncClient(
        transport=ASGITransport(app=app),
        base_url="http://test"
    ) as ac:
        yield ac
    app.dependency_overrides.clear()

Endpoint Tests

@pytest.mark.asyncio
async def test_create_user(client: AsyncClient):
    response = await client.post("/api/v1/users/", json={
        "email": "test@example.com",
        "username": "testuser",
        "password": "Test1234"
    })
    assert response.status_code == 201
    data = response.json()
    assert data["email"] == "test@example.com"
    assert "password" not in data

@pytest.mark.asyncio
async def test_get_user_not_found(client: AsyncClient):
    response = await client.get("/api/v1/users/999")
    assert response.status_code == 404

@pytest.mark.asyncio
async def test_list_users(client: AsyncClient, auth_headers: dict):
    response = await client.get("/api/v1/users/", headers=auth_headers)
    assert response.status_code == 200
    assert isinstance(response.json(), list)

Auth Helper Fixture

@pytest.fixture
async def test_user(db: AsyncSession) -> User:
    user = User(
        email="auth@test.com",
        username="authuser",
        hashed_password=hash_password("Test1234"),
    )
    db.add(user)
    await db.commit()
    await db.refresh(user)
    return user

@pytest.fixture
async def auth_headers(test_user: User) -> dict:
    token = create_access_token(sub=str(test_user.id))
    return {"Authorization": f"Bearer {token}"}

@pytest.mark.asyncio
async def test_protected_endpoint(client: AsyncClient, auth_headers: dict):
    response = await client.get("/api/v1/users/me", headers=auth_headers)
    assert response.status_code == 200

@pytest.mark.asyncio
async def test_protected_endpoint_no_auth(client: AsyncClient):
    response = await client.get("/api/v1/users/me")
    assert response.status_code == 401

Service Tests

@pytest.mark.asyncio
async def test_create_user_service(db: AsyncSession):
    user_in = UserCreate(
        email="service@test.com",
        username="serviceuser",
        password="Test1234"
    )
    user = await create_user_db(db, user_in)

    assert user.id is not None
    assert user.email == "service@test.com"

@pytest.mark.asyncio
async def test_get_user_not_found_service(db: AsyncSession):
    user = await get_user_db(db, 999)
    assert user is None

@pytest.mark.asyncio
async def test_duplicate_email(db: AsyncSession):
    user_in = UserCreate(email="dup@test.com", username="user1", password="Test1234")
    await create_user_db(db, user_in)

    with pytest.raises(IntegrityError):
        user_in2 = UserCreate(email="dup@test.com", username="user2", password="Test1234")
        await create_user_db(db, user_in2)

Mocking Dependencies

from unittest.mock import AsyncMock, patch

@pytest.mark.asyncio
async def test_with_mock_service(client: AsyncClient):
    mock_user = User(id=1, email="mock@test.com", username="mock")

    with patch("app.api.v1.users.get_user_db", new_callable=AsyncMock) as mock:
        mock.return_value = mock_user
        response = await client.get("/api/v1/users/1")
        assert response.status_code == 200
        assert response.json()["email"] == "mock@test.com"

Quick Reference

Component Purpose
@pytest.mark.asyncio Mark async test
AsyncClient HTTP client
ASGITransport(app=app) Test transport
app.dependency_overrides Override deps
AsyncMock Mock async functions
pytest.raises() Assert exception

Source: SKILL.md on GitHub

1 alert16d5 checks · Risk CRITICAL
  • Gen Agent Trust Hub16d

    The skill is an educational reference guide for FastAPI development and contains no malicious patterns or security risks. The automated alerts regarding the documentation URL are false positives, as the link belongs to the author's official GitHub pages deployment and contains standard project references.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer6mo

    1/7 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at efebc44. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 5 months ago
Other metadata
metadata
{
  "author": "https://github.com/Jeffallan",
  "version": "1.1.0",
  "domain": "backend",
  "triggers": "FastAPI, Pydantic, async Python, Python API, REST API Python, SQLAlchemy async, JWT authentication, OpenAPI, Swagger Python",
  "role": "specialist",
  "scope": "implementation",
  "output-format": "code",
  "related-skills": "fullstack-guardian, django-expert, test-master"
}
  • Python
  • fastapi
  • pydantic
  • async
  • rest-api
  • sqlalchemy
  • jwt
  • websockets
  • openapi

README badge

README badge for jeffallan/claude-skills/fastapi-expert

Implements async REST APIs, Pydantic V2 schemas, SQLAlchemy database operations, and JWT authentication with FastAPI. Covers endpoint design, dependency injection, validation, async CRUD workflows, and OpenAPI documentation generation.

Generated from the current SKILL.md.

Does this skill work with Pydantic V1?
No. The skill is built for Pydantic V2 syntax only (field_validator, model_validator, model_config). It does not support Pydantic V1 decorators like @validator.
Can I use this skill with synchronous database operations?
No. The skill assumes async/await for all I/O operations and relies on SQLAlchemy async. Mixing sync and async code improperly is explicitly forbidden.
Does this skill cover WebSocket endpoints?
Yes. WebSocket endpoint creation is listed as a core use case, though the SKILL.md does not include a detailed example.
What testing approach does this skill recommend?
The skill recommends pytest with pytest-asyncio and httpx for async testing, with OpenAPI docs verification at /docs as a checkpoint.
Does this skill include database migration tooling?
The skill covers async SQLAlchemy models and references Alembic migrations, but focuses on ORM and CRUD operations rather than migration generation.

Generated from the current SKILL.md. These answers refresh after source changes.