FastAPI Hello World application - Python Web development introductory tutorial | Daoman PythonAI

#FastAPI Hello World App

📂 Stage: Stage 1 - Rapid Foundation Building (Basics) 🔗 Prerequisite knowledge: fastapi-intro-advantages · environment-setup

Table of contents

Hello World: 5 lines to get the first interface

Let's get started and create a minimalist but complete FastAPI application. Create a new one in the project root directorymain.pydocument:

from fastapi import FastAPI  # 1. 导入核心类

app = FastAPI()  # 2. 创建应用实例(FastAPI的入口)

# 3. 定义路由装饰器(指定HTTP方法GET + 路径/)
@app.get("/")
def hello_world():  # 4. 定义路径操作函数(处理请求的核心逻辑)
    return {"message": "Hello FastAPI World!"}  # 5. 自动转JSON返回

Dismantle key logic line by line

  • Import FastAPI classes: Just like using Python's standard library, fromfastapiGet the core tools in the module.
  • Create application instance:appIt is the "brain" of the entire API, and all routing, configuration, and middleware will be mounted on it.
  • The role of decorator:@app.get("/")Accomplishes two things at the same time - tells FastAPI: "When a GET request is received and the path is the root path/**, call the followinghello_worldfunction".
  • Automatic JSON serialization: Return an ordinary Python dictionary (or object with Pydantic model), FastAPI will automatically convert it into a standard JSON format response, no need to call it manuallyjson.dumps
tip

If you have used Flask or Django before, you will find that FastAPI is simpler to write, and type hints and automatic documentation are its most eye-catching features.

Run the application and explore the automatic documentation

FastAPI officially recommends using ASGI server Uvicorn to run applications, which supports production-level features such as hot reloading and multi-processing.

Preparation: Activate virtual environment

If you have created a virtual environment in the environment-setup chapter, you need to activate it first:

  • Windows(PowerShell / CMD)
    .\venv\Scripts\activate
  • macOS / Linux
    source venv/bin/activate

Start command (development mode)

uvicorn main:app --reload --host 0.0.0.0 --port 8000

Parameter description:

  • main:app: Specifymain.pyin the fileappExample
  • --reload: Essential for development, automatically restart the server after code changes
  • --host 0.0.0.0: Allow other devices in the LAN to access (only local debugging can be omitted)
  • --port 8000: Listen to port 8000 (the default is also 8000, which can be omitted)

After successful startup, a log similar to the following will appear on the terminal:

INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [12345]
INFO:     Started server process [12346]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

📖 Free interactive API documentation

One of the most surprising features of FastAPI - automatically generated, directly interactive API documentation. After starting the service, just access the following two addresses directly:

  1. Swagger UI (debugging tool): http://127.0.0.1:8000/docs The interface is intuitive and supports sending requests online, viewing responses, and even downloading calling code snippets in multiple languages ​​(Python, JavaScript, Java, etc.).
  2. ReDoc (suitable for external display): http://127.0.0.1:8000/redoc The layout is more concise and elegant, and it is suitable as a product-level API document for teams or partners to read.
Tips

Every time you add or modify an interface, you only need to refresh the document page, and all changes will be immediately visible, which greatly improves development efficiency.

Rapidly expand core interactive functions

Hello World is just an appetizer. Next, we will quickly add three of the most commonly used interaction modes in web development to feel the simplicity and power of FastAPI.

1. Path parameters (such as obtaining a single product)

Path parameters are variables embedded in the URL path, using{}Package, FastAPI will automatically complete type conversion and basic verification:

from fastapi import FastAPI

app = FastAPI()

# 路径参数 item_id 自动转为 int 类型
@app.get("/items/{item_id}")
def get_item(item_id: int):
    return {"item_id": item_id, "item_name": f"测试商品{item_id}"}

Test it in Swagger UI:

  • inputitem_id = 123:Return normally,123is an integer
  • inputitem_id = abc: Swagger directly prompts an error, and the server returns a 422 verification failure message, which is very clear.

Query parameters are at the end of the URL?The following key-value pairs, such as/items?skip=0&limit=10. FastAPI supports optional parameters and default values:

from fastapi import FastAPI
from typing import Optional  # Python 3.10+ 可直接用 str | None

app = FastAPI()

# 所有参数都有默认值,不传也能正常使用
@app.get("/items/")
def get_items_list(
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None
):
    # 模拟数据生成
    mock_items = [{"item_id": i} for i in range(skip, skip + limit)]
    result = {"items": mock_items, "skip": skip, "limit": limit}
    if q:
        result["search_query"] = q
    return result

3. POST request body (such as creating a product)

In a POST request, the client sends data (usually JSON) to the server through the request body. FastAPI is paired with the Pydantic model to accurately define the data structure and perform strict verification - this is one of the core reasons why it can achieve high performance and low bug rate.

First define a Pydantic model to clarify the types and constraints of product fields:

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

# 请求体模型
class ItemCreate(BaseModel):
    name: str                   # 必填,字符串
    price: float                # 必填,浮点数
    description: Optional[str] = None  # 可选,默认为 None
    tax: Optional[float] = None        # 可选,默认为 None

# 用 POST 方法,接收 ItemCreate 类型的请求体
@app.post("/items/")
def create_item(item: ItemCreate):
    item_dict = item.model_dump()  # 转为字典
    if item.tax:
        item_dict["total_price"] = item.price * (1 + item.tax / 100)
    # 返回创建成功的商品,并附带自动生成的 id
    return {"item_id": 123, **item_dict}

Click "Try it out" in the Swagger UI and paste the following JSON to see the return result with the total price:

{
  "name": "机械键盘",
  "price": 399.0,
  "description": "青轴机械键盘,手感超级棒",
  "tax": 13
}

Pitfall avoidance guide and development gadgets

✅ Pitfall 1: The order of routing definitions

FastAPI performs route matching in the order defined in the code, so the fixed path needs to be placed before the variable path, otherwise matching errors may occur.

# ❌ 错误顺序:users/me 会被当成 user_id=me,引发类型错误
@app.get("/users/{user_id}")
def get_user(user_id: int): ...

@app.get("/users/me")
def get_current_user(): ...

# ✅ 正确顺序:固定路径优先匹配
@app.get("/users/me")
def get_current_user(): ...

@app.get("/users/{user_id}")
def get_user(user_id: int): ...

✅ Avoid Pitfalls 2: The Difference between Development Mode and Production Mode

  • Development Mode: Can be used--reload, can also be passed in when creating the applicationdebug=True, but these** must not appear in the production environment**.
  • Production Mode: removed--reloadanddebug=True, subsequent advanced tutorials will introduce multi-process deployment and other solutions.

🛠️ Development gadget: print request information

When debugging, you can add a simple middleware to record the method, path and response time of each request:

from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def log_request(request: Request, call_next):
    start_time = time.time()
    # 打印请求方法及路径
    print(f"📥 Request: {request.method} {request.url.path}")
    response = await call_next(request)
    process_time = (time.time() - start_time) * 1000
    # 打印响应状态码与处理耗时
    print(f"📤 Response: {response.status_code} | {process_time:.2f}ms")
    response.headers["X-Process-Time"] = f"{process_time:.2f}ms"
    return response

Put this code at the front of the application, each request will output clear logs, and the processing time will be added to the response headerX-Process-Time, which is convenient for front-end or API debugging tools to view directly.

Summary

Through this introductory tutorial that can be started in just a few minutes, you have mastered the core three-piece set of the FastAPI Hello World application:

  1. Create Application: PassFastAPI()Get application examples
  2. Define route: use@app.get/post/...()Decorator, binding HTTP methods, paths and handlers
  3. Parameters and verification: Flexibly use path parameters, query parameters and Pydantic request bodies to enjoy automatic type conversion and verification

In addition, don’t forget to make good use of Swagger UI to debug the interface in real time. It can help you save a lot of time in writing test requests.

In the next article, we will learn more about Advanced verification of path parameters and query parameters, so stay tuned ~