Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de FastAPI
FastAPI
Getting Started with FastAPIProject StructureCore ConceptsData and StateTestingDeployment
Debates

Guía de FastAPI · 2/6

Project Structure

Por ahora, este capítulo solo está disponible en inglés.

FastAPI does not impose a folder layout. A single file is a fine place to start, but as endpoints pile up you will want to split them by feature. Based on the "Bigger Applications" example from the official docs, this chapter covers a common layout, routers, configuration files and conventions.

A recommended layout

hello-fastapi/
├── app/
│   ├── __init__.py
│   ├── main.py          # creates FastAPI(), registers routers
│   ├── dependencies.py  # shared dependencies
│   ├── config.py        # settings (pydantic-settings)
│   ├── models.py        # Pydantic and SQLModel models
│   └── routers/
│       ├── __init__.py
│       ├── items.py
│       └── users.py
├── tests/
│   └── test_items.py
├── .env                 # local environment variables (not committed)
├── pyproject.toml       # or requirements.txt
└── Dockerfile

The app folder is a Python package. Every folder gets an __init__.py so imports like from app.routers import items work. Run the dev server with fastapi dev app/main.py; the fastapi command works out the package structure from the file path and finds the app object for you.

Splitting routes with APIRouter

An APIRouter behaves like a small FastAPI app. Create one per feature and give it a shared path prefix and documentation tags in one place.

# app/routers/items.py
from fastapi import APIRouter, HTTPException

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

fake_items = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}


@router.get("/")
def list_items():
    return fake_items


@router.get("/{item_id}")
def read_item(item_id: str):
    if item_id not in fake_items:
        raise HTTPException(status_code=404, detail="Item not found")
    return fake_items[item_id]

main.py then only creates the app and registers routers. The entry point stays short, and each feature's code lives in its own file.

# app/main.py
from fastapi import FastAPI

from app.routers import items, users

app = FastAPI(title="Hello FastAPI", version="0.1.0")

app.include_router(items.router)
app.include_router(users.router)


@app.get("/health")
def health():
    return {"status": "ok"}

include_router also accepts prefix, tags and dependencies, so you can mount the same router under /api/v1, or require authentication for an entire admin router.

A dependencies module

Dependencies shared by several routers belong in dependencies.py. Here is a simple check of a token in a request header:

# app/dependencies.py
from typing import Annotated

from fastapi import Header, HTTPException


async def verify_token(x_token: Annotated[str, Header()]):
    if x_token != "secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")
¿Tienes preguntas sobre este capítulo?
Capítulo anteriorGetting Started with FastAPICapítulo siguienteCore Concepts

Pass it when creating a router, as in APIRouter(dependencies=[Depends(verify_token)]), and it applies to every route on that router. The parameter name x_token is automatically mapped to the x-token header.

Dependencies and configuration files

Project dependencies usually go in pyproject.toml, which tools such as uv, Poetry and Hatch read to manage the virtual environment. If you only use pip, a requirements.txt is enough.

[project]
name = "hello-fastapi"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = [
    "fastapi[standard]",
    "sqlmodel",
    "pydantic-settings",
]

[dependency-groups]
dev = ["pytest", "ruff"]

Keep values such as database URLs and secret keys out of the code and pass them in through environment variables or a .env file. Add .env to .gitignore and commit a .env.example listing just the variable names. Chapter 4 shows how to read these settings.

Startup and shutdown

Resources that should be prepared once when the app starts and cleaned up when it stops, such as a connection pool or a machine learning model, are handled with lifespan:

from contextlib import asynccontextmanager

from fastapi import FastAPI


@asynccontextmanager
async def lifespan(app: FastAPI):
    print("starting up")    # open connections, load models
    yield
    print("shutting down")  # release resources


app = FastAPI(lifespan=lifespan)

Code before yield runs before the first request is served; code after it runs when the server stops.

Conventions

TopicConvention
Entry pointthe app variable in app/main.py
Routersone file per feature, router = APIRouter(prefix=..., tags=[...])
Modelsseparate input and output models (ItemCreate, ItemPublic)
Teststests/test_*.py, run with pytest
Secretsenvironment variables or .env, never committed

Summary

  • Start with a single main.py, then move to an app package with a routers folder as it grows.
  • Group routes per feature with APIRouter and register them with app.include_router.
  • Put shared dependencies in dependencies.py and configuration in environment variables or .env.
  • Manage startup and shutdown resources with lifespan.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.