Summary - FastAPI
- Python course
- Advanced
- Lesson 54/83
- 5 min
Combine @app.get, Pydantic and path params to write a tasks API.
Summary - FastAPI
In this group you learned the core concepts of FastAPI. FastAPI() for the app, @app.get for GET routes, BaseModel for the request body, path parameter for the URL path, query parameter for the URL query.
@app.get("/tasks/{task_id}")
def read(task_id: int, q: str = None):
return {"task_id": task_id, "q": q}In the final step you will combine all of these to write a tasks API.
Practice Tasks API
Start with from fastapi import FastAPI and from fastapi.testclient import TestClient. Define app = FastAPI(). With @app.get("/tasks/{task_id}") define def read(task_id: int, q: str = None): returning {"task_id": task_id, "q": q}. Create a client with client = TestClient(app). Print the response body with print(client.get("/tasks/5?q=ara").text).
Starter code
# bring in FastAPI from fastapi
# bring in TestClient
# define app
# add a get function at '/tasks/{task_id}' (with task_id: int, q: str = None)
# create a client with TestClient, query '/tasks/5?q=ara' and print the bodySample solution
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/tasks/{task_id}")
def read(task_id: int, q: str = None):
return {"task_id": task_id, "q": q}
client = TestClient(app)
print(client.get("/tasks/5?q=ara").text)Expected output
{"task_id":5,"q":"ara"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one declares a path parameter?
- @app.get("/items")
- @app.get("/items/{id}") Correct answer
- @app.get("/items?id=5")
- @app.get("/")
Explanation: The {id} placeholder declares a path parameter.
2 Match the group tools
| Term | Meaning |
|---|---|
FastAPI() |
Creates the app |
@app.get |
Defines a GET route |
BaseModel |
Is the request body |
{item_id} |
Is a path parameter |