0
0
FastAPIframework~30 mins

Example data in schema in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Example Data in Schema with FastAPI
📖 Scenario: You are building a simple API to share information about books. You want to make sure that when someone looks at the API documentation, they see example data for each book. This helps users understand what kind of information they can send or receive.
🎯 Goal: Create a FastAPI app with a Book schema that includes example data. This example data will show up in the API docs automatically.
📋 What You'll Learn
Create a Pydantic model called Book with fields title (string), author (string), and year (integer).
Add example data to the Book schema using Config.schema_extra.
Create a FastAPI app instance called app.
Add a POST endpoint /books/ that accepts a Book object.
💡 Why This Matters
🌍 Real World
APIs often show example data in their documentation to help developers understand how to use them. This project shows how to add that example data in FastAPI.
💼 Career
Knowing how to define schemas with example data is important for backend developers building APIs that are easy to use and well documented.
Progress0 / 4 steps
1
Create the Book schema
Create a Pydantic model called Book with these exact fields: title as a string, author as a string, and year as an integer.
FastAPI
Need a hint?

Use class Book(BaseModel): and define the fields with their types.

2
Add example data to the Book schema
Inside the Book model, add a nested Config class with a schema_extra dictionary. Add an example key with this exact data: {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "year": 1925}.
FastAPI
Need a hint?

Define a nested Config class inside Book and add schema_extra with the example dictionary.

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

Import FastAPI and create app = FastAPI().

4
Add POST endpoint to accept Book data
Add a POST endpoint at /books/ using @app.post("/books/"). The function should be called create_book and accept a parameter book of type Book. Return the book object.
FastAPI
Need a hint?

Use @app.post("/books/") decorator and define an async function create_book that takes book: Book and returns it.