0
0
FastAPIframework~30 mins

Request body declaration in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Request Body Declaration in FastAPI
📖 Scenario: You are building a simple API to receive user information for a newsletter subscription.The API should accept user data in the request body and process it.
🎯 Goal: Build a FastAPI endpoint that declares a request body using a Pydantic model to receive user data.
📋 What You'll Learn
Create a Pydantic model named User with fields name (string) and email (string).
Create a FastAPI app instance named app.
Create a POST endpoint at /subscribe that accepts a User object as the request body.
Return the received user data as JSON in the response.
💡 Why This Matters
🌍 Real World
APIs often need to receive structured data from clients. Declaring request bodies clearly helps validate and process this data safely.
💼 Career
Knowing how to declare request bodies with Pydantic models in FastAPI is essential for backend developers building modern web APIs.
Progress0 / 4 steps
1
Create the User model
Create a Pydantic model called User with two fields: name of type str and email of type str.
FastAPI
Need a hint?

Use class User(BaseModel): and define name and email as string fields.

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

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

3
Create the POST endpoint with request body
Create a POST endpoint at /subscribe using @app.post("/subscribe"). Define a function subscribe that takes a parameter user of type User to receive the request body.
FastAPI
Need a hint?

Use @app.post("/subscribe") decorator and define subscribe(user: User) function that returns user.

4
Complete the FastAPI app
Ensure the full code includes the User model, the app instance, and the /subscribe POST endpoint returning the user data.
FastAPI
Need a hint?

Make sure all parts are included and correctly indented.