0
0
FastAPIframework~30 mins

Response model declaration in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Response Model Declaration in FastAPI
📖 Scenario: You are building a simple API to share information about books. You want to make sure the API only sends back the right details about each book to users.
🎯 Goal: Create a FastAPI app that defines a response model using pydantic. The API should return book data with only the specified fields.
📋 What You'll Learn
Create a Book model using pydantic.BaseModel with fields title (string) and author (string).
Create a FastAPI app instance called app.
Create a GET endpoint /book that returns a Book instance.
Use the response_model parameter in the route decorator to declare the response model.
💡 Why This Matters
🌍 Real World
APIs often need to send back data in a clear, consistent format. Response models help define exactly what data clients receive.
💼 Career
Knowing how to declare response models in FastAPI is essential for backend developers building reliable and maintainable APIs.
Progress0 / 4 steps
1
Create the Book model
Create a Book class that inherits from pydantic.BaseModel. It should have two string fields: title and author.
FastAPI
Need a hint?

Use class Book(BaseModel): and define title and author as string fields.

2
Create the FastAPI app
Import FastAPI and create an app instance called app.
FastAPI
Need a hint?

Use app = FastAPI() to create the app instance.

3
Create the GET endpoint with response model
Create a GET endpoint /book using @app.get. Use the response_model=Book parameter. The endpoint should return a Book instance with title set to 'The Great Gatsby' and author set to 'F. Scott Fitzgerald'.
FastAPI
Need a hint?

Use @app.get("/book", response_model=Book) and return a Book instance with the given title and author.

4
Complete the FastAPI app
Make sure the full code includes the Book model, the app instance, and the GET endpoint /book with the response model declared.
FastAPI
Need a hint?

Check that all parts are included: model, app, and endpoint with response model.