0
0
FastAPIframework~30 mins

Multiple response types in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Multiple Response Types with FastAPI
📖 Scenario: You are building a simple web API that can return different types of responses depending on the request. Sometimes it returns plain text, sometimes JSON data.
🎯 Goal: Create a FastAPI app with one endpoint /response that returns either plain text or JSON depending on a query parameter.
📋 What You'll Learn
Create a FastAPI app instance called app
Add a GET endpoint /response with a query parameter type
If type is text, return plain text response
If type is json, return JSON response with a dictionary
Use correct FastAPI response types for each case
💡 Why This Matters
🌍 Real World
APIs often need to return different formats like JSON or plain text depending on client needs.
💼 Career
Knowing how to handle multiple response types is important for backend developers building flexible APIs.
Progress0 / 4 steps
1
Create FastAPI app instance
Create a FastAPI app instance called app by importing FastAPI and initializing it.
FastAPI
Need a hint?

Use FastAPI() to create the app instance and assign it to app.

2
Add GET endpoint with query parameter
Add a GET endpoint /response to the app that accepts a query parameter called type of type str.
FastAPI
Need a hint?

Use @app.get("/response") decorator and define an async function with type: str parameter.

3
Return plain text or JSON based on query parameter
Inside the get_response function, return plain text 'This is plain text' if type equals 'text'. Otherwise, return a JSON dictionary {"message": "This is JSON"}.
FastAPI
Need a hint?

Use an if statement to check type and return the correct response.

4
Use correct response classes for text and JSON
Import PlainTextResponse from fastapi.responses and update the get_response function to return PlainTextResponse with the text when type is 'text'. Return the JSON dictionary directly otherwise.
FastAPI
Need a hint?

Use PlainTextResponse to send plain text responses properly in FastAPI.