AdSense

網頁

2025/6/16

Python FastAPI Hello World

Python使用FastAPI建立網路應用程式。


FastAPI簡介

FastAPI是Python常用的Web應用程式框架(framework)之一,主要用於API服務的搭建,,另外兩個常見的Web框架為Django和Flask


環境

  • Windows 11 Pro
  • Python 3.13.3


建立專案

本範例使用PDM建立專案,參考「Python PDM建立新專案」。


下載FastAPI

在命令列輸入pip install "fastapi[standard]"下載並安裝FastAPI及FastAPI CLI

C:\>pip install "fastapi[standard]"
Collecting fastapi[standard]
  Downloading fastapi-0.115.12-py3-none-any.whl.metadata (27 kB)
...
Installing collected packages: websockets, typing-extensions, sniffio, shellingham, pyyaml, python-multipart, python-dotenv, pygments, mdurl, MarkupSafe, idna, httptools, h11, dnspython, colorama, certifi, annotated-types, typing-inspection, pydantic-core, markdown-it-py, jinja2, httpcore, email-validator, click, anyio, watchfiles, uvicorn, starlette, rich, pydantic, httpx, typer, rich-toolkit, fastapi, fastapi-cli
Successfully installed MarkupSafe-3.0.2 annotated-types-0.7.0 anyio-4.9.0 certifi-2025.6.15 click-8.2.1 colorama-0.4.6 dnspython-2.7.0 email-validator-2.2.0 fastapi-0.115.12 fastapi-cli-0.0.7 h11-0.16.0 httpcore-1.0.9 httptools-0.6.4 httpx-0.28.1 idna-3.10 jinja2-3.1.6 markdown-it-py-3.0.0 mdurl-0.1.2 pydantic-2.11.7 pydantic-core-2.33.2 pygments-2.19.1 python-dotenv-1.1.0 python-multipart-0.0.20 pyyaml-6.0.2 rich-14.0.0 rich-toolkit-0.14.7 shellingham-1.5.4 sniffio-1.3.1 starlette-0.46.2 typer-0.16.0 typing-extensions-4.14.0 typing-inspection-0.4.1 uvicorn-0.34.3 watchfiles-1.1.0 websockets-15.0.1


在專案根目錄以命令列輸入pdm add fastapi下載並安裝FastAPI套件至專案。

C:\..\demo>pdm add fastapi
Adding packages to default dependencies: fastapi
  0:00:18 🔒 Lock successful.
Changes are written to pyproject.toml.
Synchronizing working set with resolved packages: 10 to add, 0 to update, 0 to remove

  ✔ Install annotated-types 0.7.0 successful
  ✔ Install sniffio 1.3.1 successful
  ✔ Install typing-inspection 0.4.1 successful
  ✔ Install typing-extensions 4.14.0 successful
  ✔ Install idna 3.10 successful
  ✔ Install starlette 0.46.2 successful
  ✔ Install anyio 4.9.0 successful
  ✔ Install fastapi 0.115.12 successful
  ✔ Install pydantic 2.11.7 successful
  ✔ Install pydantic-core 2.33.2 successful

  0:00:09 🎉 All complete! 10/10


建立主程式

在專案根目錄建立main.py內容如下。

main.py

from typing import Union

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}

github



啟動專案

在專案根目錄輸入fastapi dev main.py啟動專案。

C:\..\demo>fastapi dev main.py

   FastAPI   Starting development server 🚀

             Searching for package file structure from directories with __init__.py files
             Importing from C:\Users\bronx\Documents\py-workspace\demo

    module   🐍 main.py

      code   Importing the FastAPI app object from the module with the following code:

             from main import app

       app   Using import string: main:app

    server   Server started at http://127.0.0.1:8000
    server   Documentation at http://127.0.0.1:8000/docs

       tip   Running in development mode, for production use: fastapi run

             Logs:

      INFO   Will watch for changes in these directories: ['C:\\..\\demo']
      INFO   Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
      INFO   Started reloader process [22024] using WatchFiles
      INFO   Started server process [4812]
      INFO   Waiting for application startup.
      INFO   Application startup complete.


測試

在瀏覽器url輸入http://127.0.0.1:8000返回以下結果。

{"Hello":"World"}

在瀏覽器url輸入http://127.0.0.1:8000/items/5?q=somequery返回以下結果。

{"item_id":5,"q":"somequery"}

在瀏覽器url輸入http://127.0.0.1:8000/docs開啟OpenAPI文件。

沒有留言:

AdSense