跳至主要內容
產品桌面工具TASTECAD圖面檢視TASTEFILES檔案管理TASTEFTP檔案傳輸TASTESSH遠端工作空間TASTEZIP壓縮與解壓縮TASTEWINM檔案管理開發工具TASTECODERust 整合開發環境TASTESTUDIO整合開發與測試環境TASTEETL資料整合(ETL)伺服器TASTEREMOTE遠端桌面伺服器TASTEGEO空間資訊伺服器TASTEMAIL郵件工作空間投資TASTESTOCK股票自動交易桌面應用程式開始使用下載文件購買所有產品
市集
資訊
技術資訊今日開發資訊開發文件程式語言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular伺服器框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express應用程式與桌面框架TauriFlutterReact NativeElectron演算法演算法基礎核心演算法進階演算法實務演算法
社群專案開發日誌提示詞AI 工具問題作品展示社群指南
合作技術傳授網站建置桌面應用程式建置發布與付款流程銷售合作夥伴聯絡我們
服務遠端桌面安裝包客製
TASTEDEV
產品

桌面工具

TASTECAD再複雜的圖面,也能輕鬆開啟TASTEFILES只挑需要的檔案,最快送達TASTEFTP讓檔案往來,走最俐落的路TASTESSH在你與伺服器之間,築起更穩固的連線TASTEZIP壓得更快,解得更安心TASTEWINM以鍵盤為主、用兩個窗格整理檔案的檔案管理器

開發工具

TASTECODE在一個視窗中完成 Rust 應用程式的編輯、建置、偵錯與測試TASTESTUDIO從編輯到遠端測試,再到經核准的 AI 修正TASTEETL邊看數值,邊搬資料

伺服器

TASTEREMOTE在自己的伺服器上運行的遠端桌面TASTEGEO以 Rust 重新打造相容 GeoServer 的空間資訊伺服器TASTEMAIL把郵件的主導權拿回自己手上

投資

TASTESTOCK何時、做什麼——依你訂下的規則運作的股票自動交易

開始使用

下載所有產品的最新版本文件各產品使用方法購買訂閱與永久授權所有產品一覽全部產品
所有產品
市集資訊
技術

資訊

今日開發資訊語言、框架、GitHub 與 AI 官方發布開發文件語言、框架與演算法指南

程式語言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
伺服器框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
應用程式與桌面框架TauriFlutterReact NativeElectron

演算法

演算法基礎複雜度分析 · 排序 · 搜尋 · 基礎資料結構 · 樹與堆積核心演算法圖形走訪 · 最短路徑與最小生成樹 · 動態規劃 · 貪婪演算法 · 分治法 · 回溯法進階演算法字串演算法 · 數學與數論 · 位元運算 · 線段樹 · 併查集實務演算法程式面試解題策略 · LRU 快取 · 速率限制 · 一致性雜湊
查看全部開發文件
社群
專案探索開發者與作品開發日誌決策與試錯提示詞可重複使用的指令AI 工具問題Claude、Codex、Gemini 的問題與替代做法作品展示已完成的成果社群指南我們如何公開打造
合作
技術傳授用 Rust 與 egui 打造原生應用程式網站建置10 種語言、帳號、文件與下載桌面應用程式建置Rust 與 egui,不用 WebView發布與付款流程簽章、MSI、deb、rpm、AppImage、雜湊銷售合作夥伴推薦即得 30%聯絡我們開發、合作與投資諮詢
服務
遠端桌面用瀏覽器連線你的電腦安裝包客製只裝需要的,設定預先放好
購買
繁
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登入
登入
TASTEDEV

從小工具到更好的開發。

support@tastedev.net支持 TASTEDEV
產品產品系列購買文件下載市集客戶支援
社群專案開發日誌提示詞AI 工具問題作品展示
政策關於我們隱私權政策服務條款訂閱條款退款政策社群規範
帳戶登入註冊
訪客
今天
昨天
累計瀏覽
公司名稱
GXSOFT
負責人
CHOI YOUNG GU
營業登記號碼
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
電子郵件
whitecalvin@tastedev.net
個人資料保護負責人
CHOI YOUNG GU

© 2026 TASTEDEV產品資訊以經驗證的開發原始碼為準。已發布·持續改進

FastAPI 文件
FastAPI
Getting Started with FastAPIProject StructureCore ConceptsData and StateTestingDeployment
討論

FastAPI 指南 · 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())
對本章有疑問嗎?
上一章Project Structure下一章Data 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 則留言

熱門留言由新到舊

登入 · 登入後即可留言。