home / skills / first-fluke / fullstack-starter / fastapi-router-creator

fastapi-router-creator skill

/.agents/skills/fastapi-router-creator

This skill guides modular and file-based FastAPI routing to improve maintainability and scalability across complex APIs.

npx playbooks add skill first-fluke/fullstack-starter --skill fastapi-router-creator

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
1.8 KB
---
name: fastapi-router-creator
description: Guide for creating and organizing FastAPI routes using a file-based routing system or modular router pattern. Helps organize complex API structures.
---

# FastAPI Router Creator

This skill guides the creation of modular, organized FastAPI routers, emphasizing maintainability and scalability.

## Routing Strategies

### 1. Modular Router Pattern (Standard)

The most common and recommended approach for FastAPI.

**Structure:**
```
src/api/v1/endpoints/
├── users.py
├── items.py
└── auth.py
```

**Implementation:**

`src/api/v1/endpoints/users.py`:
```python
from fastapi import APIRouter

router = APIRouter()

@router.get("/")
async def get_users():
    ...
```

`src/api/v1/api.py` (Aggregator):
```python
from fastapi import APIRouter
from src.api.v1.endpoints import users, items

api_router = APIRouter()
api_router.include_router(users.router, prefix="/users", tags=["users"])
api_router.include_router(items.router, prefix="/items", tags=["items"])
```

### 2. File-Based Routing (fastapi-router)

For a Next.js-like experience where file structure dictates URLs. (Requires `fastapi-router` library or custom walker).

**Structure:**
```
src/app/
├── api/
│   ├── users/
│   │   ├── route.py  # Handles /api/users
│   │   └── [id]/
│   │       └── route.py # Handles /api/users/{id}
```

## Best Practices

1.  **Prefixing**: Use prefixes at the router include level, not inside every endpoint decorator.
2.  **Tags**: Use tags to group endpoints in OpenAPI docs.
3.  **Dependencies**: Apply dependencies (like auth) at the router level if they apply to all endpoints in that router.
    ```python
    router = APIRouter(dependencies=[Depends(get_current_active_user)])
    ```
4.  **Version**: Namespace routers by API version (`v1`, `v2`).

Overview

This skill guides creating and organizing FastAPI routes using either a modular router pattern or a file-based routing system. It focuses on maintainability, clear URL structure, and scalable API versioning for production applications. The guidance is practical and framework-agnostic, showing patterns that fit monorepo and microservice setups.

How this skill works

The skill describes two complementary approaches: a modular router pattern where APIRouters live in endpoint modules and are aggregated, and a file-based routing approach where folder and file names map to URL paths (Next.js-style). It explains router inclusion, prefixing, tagging, dependency injection at router level, and version namespacing to keep routes organized and discoverable. Example code snippets and directory layouts illustrate implementation details and integration points.

When to use it

  • You need clear separation of concerns for large FastAPI projects or monorepos.
  • You want predictable URL structure that follows filesystem layout (Next.js-like routing).
  • You plan to apply shared dependencies, authentication, or middleware per route group.
  • You need API versioning with minimal friction across many endpoints.
  • You require OpenAPI-friendly grouping and readable documentation for teams.

Best practices

  • Include routers with a shared prefix at the aggregator level rather than repeating prefixes on each endpoint.
  • Apply common dependencies (auth, DB sessions) at the APIRouter level to avoid duplication.
  • Use tags to group endpoints for clearer OpenAPI docs and faster discovery.
  • Namespace by version (e.g., /api/v1) to enable safe, parallel evolution of the API.
  • Keep endpoint files focused (one resource per file) to improve testability and readability.

Example use cases

  • A monorepo serving multiple frontends where backend routes must mirror Next.js file structure.
  • A microservice that needs router-level authentication and a clear versioning strategy.
  • Rapid prototyping where file-based routing accelerates iteration and reduces boilerplate.
  • Large teams working on distinct domains (users, items, auth) that benefit from modular routers.
  • Migrating a monolithic API to versioned modules to support backward compatibility.

FAQ

Should I prefer modular routers or file-based routing?

Use modular routers for explicit control and testability. Use file-based routing when you want filesystem-driven URL mapping and faster developer ergonomics; both can coexist.

Where should I apply authentication and common dependencies?

Apply them at the APIRouter level with the dependencies parameter so all endpoints in that router inherit them without repeating logic.