Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneTASTEWINMGestione fileStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailInvestimentiTASTESTOCKApp desktop di trading automatico azionarioIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuroTASTEWINMUn file manager a due pannelli pensato per la tastiera

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Investimenti

TASTESTOCKTrading automatico azionario secondo le regole che decidi tu: quando e che cosa

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeChi siamoInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
Ieri
Visualizzazioni totali
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di FastAPI
FastAPI
Getting Started with FastAPIProject StructureCore ConceptsData and StateTestingDeployment
Discussioni

Guida a FastAPI · 3/6

Core Concepts

Per ora questo capitolo è disponibile solo in inglese.

Almost everything in FastAPI follows from one idea: declare it with type hints and the framework handles the rest. This chapter walks through path operations, path, query and body parameters, Pydantic models and validation, dependency injection, async def versus def, and the OpenAPI docs.

Path operations

FastAPI calls the combination of an HTTP method and a path a path operation. You declare one with @app.get, @app.post, @app.put, @app.patch or @app.delete, and that is also where you set the status code and response model.

from fastapi import FastAPI, HTTPException, status

app = FastAPI()
items: dict[int, str] = {1: "Keyboard"}


@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    del items[item_id]

Raising HTTPException stops processing immediately and returns the given status code with a {"detail": ...} JSON body. Routes are matched in the order they are declared, so a fixed path such as /users/me must come before /users/{user_id}.

Path and query parameters

A function parameter whose name matches a {name} in the path is a path parameter; any other parameter with a simple type is a query parameter. Extra validation rules are attached with Annotated plus Path or Query.

from typing import Annotated

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/users/{user_id}/items")
def list_user_items(
    user_id: Annotated[int, Path(ge=1)],
    q: Annotated[str | None, Query(max_length=50)] = None,
    skip: int = 0,
    limit: Annotated[int, Query(le=100)] = 10,
):
    return {"user_id": user_id, "q": q, "skip": skip, "limit": limit}

A parameter without a default is required; one with a default is optional. Constraints such as ge, le, min_length and pattern drive validation and show up in the OpenAPI docs as well.

Request bodies and Pydantic models

JSON bodies are declared as classes that inherit from Pydantic's BaseModel. When a parameter's type is a Pydantic model, FastAPI reads it from the request body.

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class ItemCreate(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    price: float = Field(gt=0)
    tags: list[str] = []


class ItemPublic(BaseModel):
    id: int
    name: str
    price: float


@app.post("/items", response_model=ItemPublic, status_code=201)
def create_item(item: ItemCreate):
    return ItemPublic(id=1, **item.model_dump())
Domande su questo capitolo?
Capitolo precedenteProject StructureCapitolo successivoData and State

If the body is not valid JSON or price is negative, the client automatically gets a 422 response. response_model filters the output down to that model's shape, which keeps fields that only belong on input, such as passwords, from leaking into responses. A return annotation (-> ItemPublic) achieves the same thing.

Dependency injection

Depends is FastAPI's dependency injection mechanism. Declare a function (or class) as a dependency and FastAPI calls it for each request and passes the result to your path operation. Dependencies can take path and query parameters of their own and can depend on other dependencies.

from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()


def pagination(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}


Pagination = Annotated[dict, Depends(pagination)]


@app.get("/items")
def list_items(page: Pagination):
    return {"page": page}


@app.get("/users")
def list_users(page: Pagination):
    return {"page": page}

An Annotated type alias lets several routes reuse the same dependency with very little code. Dependencies that use yield can run cleanup code after the response, which is why they are the usual way to manage database sessions (chapter 4). Authentication, permission checks and shared parameters are typically implemented as dependencies too.

async def versus def

Path operations can be declared with either async def or plain def, and FastAPI runs them differently:

DeclarationHow it runsUse it when
async defdirectly on the event loopyou call awaitable async libraries (HTTPX, asyncpg and so on)
defin a separate thread poolyou call blocking libraries (classic DB drivers, file processing)

The trap to avoid is calling blocking code, such as time.sleep() or a synchronous database call, inside an async def function: it stalls the entire event loop. When in doubt, plain def is the safer choice.

import httpx
from fastapi import FastAPI

app = FastAPI()


@app.get("/weather")
async def weather():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://example.com/api/weather")
    return response.json()

Polishing the OpenAPI docs

FastAPI collects every declaration above into an OpenAPI schema. Arguments such as summary, description, tags and deprecated make the docs friendlier, and a function's docstring becomes its description. Set the app's title and version with FastAPI(title=..., version=...).

Summary

  • Declare path operations with decorators and return errors with HTTPException.
  • Validate path and query parameters with type hints, Annotated, Path and Query.
  • Define request bodies and response shapes with Pydantic models and filter output with response_model.
  • Factor shared logic into Depends, and keep blocking code in plain def functions.

0 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.