Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

FastAPI docs
FastAPI
Getting Started with FastAPIProject StructureCore ConceptsData and StateTestingDeployment
Discussions

FastAPI guide · 3/6

Core Concepts

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())

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.
Questions about this chapter?
Previous chapterProject StructureNext chapterData and State

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.