FastAPI First Application
This section takes you through a complete example to create a FastAPI application from scratch and understand the meaning of each line of code.
Minimal application
Create a file named main.py and add the following code:
Example
from
fastapi
import
FastAPI
Step 1: Import the FastAPI class
Step 2: Create an application instance
app
=
FastAPI
(
)
Step 3: Define the path operation decorator
Step 4: Define the path operation function
@
app.
get
(
"/"
)
async
def
root
(
)
:
Step 5: Return the response content
return
{
"message"
:
"Hello World"
}
Start the app:
$ uvicorn main:app --reload
Access the http://127.0.0.1:8000, returns:
{"message": "Hello World"}
Code breakdown
1. Import FastAPI
from fastapi import FastAPI
FastAPI is a Python class that provides all the core functionality for your API. It directly inherits from Starlette, so you can also use all of Starlette's features.
2. Create an application instance
app = FastAPI()
Create a FastAPI instance; the variable name is usually app. This instance is the main object for creating all APIs. Unlike Flask, FastAPI does not need to pass __name__ parameter was added.
3. Define the path operation decorator
@app.get("/")
This line tells FastAPI: when a user accesses the root path / via the GET method, execute the function below.
Two concepts are involved here:
| Concept | Description | Example |
|---|---|---|
| Path | In the URL, the part from the first / onward, also known as the "endpoint" or "route" |
/items/foo |
| Operation | HTTP method, corresponding to different operation semantics | GET、POST、PUT、DELETE |
FastAPI supports decorators for all HTTP methods:
| Decorator | HTTP methods | Common Use Cases |
|---|---|---|
@app.get() |
GET | Get/read data |
@app.post() |
POST | Create new data |
@app.put() |
PUT | Fully update data |
@app.patch() |
PATCH | Partially update data |
@app.delete() |
DELETE | Delete data |
4. Define the path operation function
async def root():
This is the path operation function, called whenever FastAPI receives a GET / request. The function name can be anything, but a meaningful name is recommended.
You can use the
async defor a regulardefto define the function. FastAPI automatically handles the difference between the two. If you are not familiar with async programming, use a regulardefis sufficient; later chapters will cover async in detail.
5. Return the response content
return {"message": "Hello World"}
The function returns a dictionary, which FastAPI automatically converts to a JSON response. You can return dict、list、str、int and other types; FastAPI handles the JSON conversion automatically.
Add more routes
Next, we add path parameters and query parameters to enrich the application's functionality:
Example
from
fastapi
import
FastAPI
app
=
FastAPI
(
)
@
app.
get
(
"/"
)
async
def
root
(
)
:
"""Root path, returns a welcome message"""
return
{
"message"
:
"Hello World"
}
@
app.
get
(
"/items/{item_id}"
)
async
def
read_item
(
item_id:
int
,
q:
str
|
None
=
None
)
:
"""Get an item by ID, supports the optional query parameter q"""
return
{
"item_id"
: item_id
,
"q"
: q
}
Description of the new route's parameters:
| Parameters | Type | Source | Description |
|---|---|---|---|
item_id |
int |
Path parameters | Taken from the URL path; FastAPI automatically converts the string to an integer |
q |
str \| None |
Query Parameters | From the URL's ?q=xxx part, with a default value of None, meaning optional |
Access test:
# 访问根路径
GET http://127.0.0.1:8000/
响应: {"message": "Hello World"}
# Accessing routes with path parameters
GET http://127.0.0.1:8000/items/5
响应: {"item_id": 5, "q": null}
# Pass both path parameters and query parameters
GET http://127.0.0.1:8000/items/5?q=runoob
响应: {"item_id": 5, "q": "runoob"}
Note item_id value is an integer 5 rather than a string "5", this is FastAPI's data conversion feature based on type declarations. If a non-integer is passed (e.g. /items/foo), FastAPI returns a clear validation error message.
Add a POST request
Next, we add a POST route that uses a request body:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
app
=
FastAPI
(
)
Define the request body data model
class
Item
(
BaseModel
)
:
name:
str
Required: item name
description:
str
|
None
=
None
Optional: item description
price:
float
Required: item price
tax:
float
|
None
=
None
Optional: tax
@
app.
post
(
"/items/"
)
async
def
create_item
(
item: Item
)
:
"""Create a new item, accepts a JSON request body"""
return
item
@
app.
put
(
"/items/{item_id}"
)
async
def
update_item
(
item_id:
int
,
item: Item
)
:
"""Update a specified item, using both path parameters and a request body"""
return
{
"item_id"
: item_id
,
"item_name"
: item.
name
}
Here, Pydantic's BaseModel is used to define the structure of the request body. FastAPI automatically:
- parses the JSON data in the request into
Itemobject - validates data types and required fields
- displays the request body structure in the API documentation
Pydantic is a core dependency of FastAPI, used for data validation and serialization. Later chapters will cover its usage in detail.
FastAPI parameter recognition rules
FastAPI automatically recognizes parameters through the following rules Source:
| Parameter source | Recognition condition | Example |
|---|---|---|
| Path parameters | The parameter name appears in the route's path {} Medium |
item_id in /items/{item_id} Medium |
| Query Parameters | The parameter is a single type (int、str、bool etc.) |
q: str \| None = None |
| Request body | The parameter type is a Pydantic model | item: Item |
You can mix these three types of parameters in the same function, and FastAPI automatically gets data from the correct location.
Summary
Core steps to create a FastAPI application:
- Import
FastAPI - Create application instance
app = FastAPI() - Use decorators (such as
@app.get()) to define path operations - Define path operation functions, declaring parameters with type annotations
- Use
uvicorn main:app --reloadRun the Development Server