FastAPI is a modern Python web framework designed for building high-performance APIs with minimal code. Understanding how to use the core HTTP methods—GET, POST, PUT, and DELETE—is essential for creating clean and RESTful endpoints. This post will walk through the basic usage of each method in FastAPI with practical code examples.
The code below is used to print information about the response.(log_response_info)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| import aiohttp
from aiohttp import ClientResponseError
async def log_response_info(response: aiohttp.ClientResponse):
print("\n[Response Info]")
print(f"Status : {response.status} {response.reason}")
print(f"URL : {response.url}")
print(f"Method : {response.method}")
print(f"Content-Type : {response.content_type}")
print(f"Charset : {response.charset}")
print(f"Cookies : {dict(response.cookies)}")
print(f"Headers:")
pprint(dict(response.headers))
print(f"OK? : {response.ok}")
try:
data = await response.json()
print(f"\nJSON Body:")
print(f"type(data): {type(data)}")
print(data)
except aiohttp.ContentTypeError:
text = await response.text()
print(f"\nText Body:\n{text}")
|
GET
The GET
method is used to request data from the server. It’s commonly used to fetch a resource or list of resources.
1
2
3
4
5
6
7
8
9
10
11
12
13
| @router.get("/task/")
async def get_task2(
question: Optional[str] = None, user_name: Optional[str] = None
):
try:
result = {
"result": "get_task2 ok",
"question": question,
"user_name": user_name,
}
return result
except SQLAlchemyError as e:
raise HTTPException(status_code=500, detail=str(e))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| try:
url = "http://127.0.0.1:7249/ds2man/basic/task/"
data = {
"question": "Hello",
"user_name": "DS2Man"
}
async with aiohttp.ClientSession(
trust_env=True, timeout=aiohttp.ClientTimeout(total=120)
) as session:
# async with session.get(url, json=data) as response: # GET and DELETE requests do not allow a body. Be careful!
async with session.get(url, params=data) as response: # Therefore, the data must be passed as parameters.
response.raise_for_status()
await log_response_info(response)
except ClientResponseError as e:
print(f"[ClientResponseError] {e.status}: {e.message}")
except Exception as e:
print(f"[Unhandled Exception] {e}")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| [Response Info]
Status : 200 OK
URL : http://127.0.0.1:7249/ds2man/basic/task/?question=Hello&user_name=DS2Man
Method : GET
Content-Type : application/json
Charset : None
Cookies : {}
Headers:
{'Content-Length': '65',
'Content-Type': 'application/json',
'Date': 'Sat, 03 May 2025 00:39:56 GMT',
'Server': 'uvicorn'}
OK? : True
JSON Body:
type(data): <class 'dict'>
{'result': 'get_task2 ok', 'question': 'Hello', 'user_name': 'DS2Man'}
|
POST
The POST
method is used to create a new resource on the server. It’s often used with JSON payloads.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| class MsgInfo(BaseModel):
question: str
user_name: str
@router.post("/task/")
async def post_task1(msginfo: MsgInfo):
try:
result = {
"result": "post_task1 ok",
"question": msginfo.question,
"user_name": msginfo.user_name,
}
return result
except SQLAlchemyError as e:
raise HTTPException(status_code=500, detail=str(e))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| try:
url = "http://127.0.0.1:7249/ds2man/basic/task/"
data = {
"question": "Hello",
"user_name": "DS2Man"
}
async with aiohttp.ClientSession(
trust_env=True, timeout=aiohttp.ClientTimeout(total=120)
) as session:
async with session.post(url, json=data) as response:
response.raise_for_status()
await log_response_info(response)
except ClientResponseError as e:
print(f"[ClientResponseError] {e.status}: {e.message}")
except Exception as e:
print(f"[Unhandled Exception] {e}")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| [Response Info]
Status : 200 OK
URL : http://127.0.0.1:7249/ds2man/basic/task/
Method : POST
Content-Type : application/json
Charset : None
Cookies : {}
Headers:
{'Content-Length': '66',
'Content-Type': 'application/json',
'Date': 'Sat, 03 May 2025 00:41:30 GMT',
'Server': 'uvicorn'}
OK? : True
JSON Body:
type(data): <class 'dict'>
{'result': 'post_task1 ok', 'question': 'Hello', 'user_name': 'DS2Man'}
|
PUT
The PUT
method is used to update an existing resource completely.
1
2
3
4
5
6
7
8
9
10
11
12
| @router.put("/task/")
async def put_task1(msginfo: MsgInfo):
try:
result = {
"result": "put_task1 ok",
"question": msginfo.question,
"user_name": msginfo.user_name,
}
return result
except SQLAlchemyError as e:
raise HTTPException(status_code=500, detail=str(e))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| try:
url = "http://127.0.0.1:7249/ds2man/basic/task/"
data = {
"question": "Hello",
"user_name": "DS2Man"
}
async with aiohttp.ClientSession(
trust_env=True, timeout=aiohttp.ClientTimeout(total=120)
) as session:
async with session.put(url, json=data) as response:
response.raise_for_status()
await log_response_info(response)
except ClientResponseError as e:
print(f"[ClientResponseError] {e.status}: {e.message}")
except Exception as e:
print(f"[Unhandled Exception] {e}")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| [Response Info]
Status : 200 OK
URL : http://127.0.0.1:7249/ds2man/basic/task/
Method : PUT
Content-Type : application/json
Charset : None
Cookies : {}
Headers:
{'Content-Length': '65',
'Content-Type': 'application/json',
'Date': 'Sat, 03 May 2025 00:42:04 GMT',
'Server': 'uvicorn'}
OK? : True
JSON Body:
type(data): <class 'dict'>
{'result': 'put_task1 ok', 'question': 'Hello', 'user_name': 'DS2Man'}
|
DELETE
The DELETE
method removes a resource from the server.
1
2
3
4
5
6
7
8
9
10
11
12
13
| @router.delete("/task/")
async def delete_task1(
question: Optional[str] = None, user_name: Optional[str] = None
):
try:
result = {
"result": "delete_task1 ok",
"question": question,
"user_name": user_name,
}
return result
except SQLAlchemyError as e:
raise HTTPException(status_code=500, detail=str(e))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| try:
url = "http://127.0.0.1:7249/ds2man/basic/task/"
data = {
"question": "Hello",
"user_name": "DS2Man"
}
async with aiohttp.ClientSession(
trust_env=True, timeout=aiohttp.ClientTimeout(total=120)
) as session:
# async with session.delete(url, json=data) as response: # GET and DELETE requests do not allow a body. Be careful!
async with session.delete(url, params=data) as response: # Therefore, the data must be passed as parameters.
response.raise_for_status()
await log_response_info(response)
except ClientResponseError as e:
print(f"[ClientResponseError] {e.status}: {e.message}")
except Exception as e:
print(f"[Unhandled Exception] {e}")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| [Response Info]
Status : 200 OK
URL : http://127.0.0.1:7249/ds2man/basic/task/?question=Hello&user_name=DS2Man
Method : DELETE
Content-Type : application/json
Charset : None
Cookies : {}
Headers:
{'Content-Length': '68',
'Content-Type': 'application/json',
'Date': 'Sat, 03 May 2025 00:43:33 GMT',
'Server': 'uvicorn'}
OK? : True
JSON Body:
type(data): <class 'dict'>
{'result': 'delete_task1 ok', 'question': 'Hello', 'user_name': 'DS2Man'}
|
Summary Table
Method | Purpose | Decorator | Body Needed? | e.g. code | Use Case |
---|
GET | Read resource | @app.get | No | get(url, params=data) | Retrieve data |
POST | Create resource | @app.post | Yes | post(url, json=data) | Submit new data |
PUT | Update resource | @app.put | Yes | put(url, json=data) | Replace existing resource |
DELETE | Delete resource | @app.delete | No | delete(url, params=data) | Remove resource |