We send and receive messages to let different parts of a program or different programs talk to each other. FastAPI helps us do this easily over the web.
Sending and receiving messages in FastAPI
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Message(BaseModel): content: str @app.post("/send-message") async def send_message(message: Message): return {"received_message": message.content} @app.get("/receive-message") async def receive_message(): return {"message": "Hello from FastAPI!"}
Use @app.post to create an endpoint that receives messages.
Use Pydantic models to define the structure of messages for validation.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Message(BaseModel): content: str @app.post("/send-message") async def send_message(message: Message): return {"received_message": message.content}
@app.get("/receive-message") async def receive_message(): return {"message": "Hello from FastAPI!"}
This program lets you send messages to the server with POST requests and stores them in a list. You can then get all stored messages with a GET request.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Message(BaseModel): content: str messages = [] @app.post("/send-message") async def send_message(message: Message): messages.append(message.content) return {"status": "Message received", "message": message.content} @app.get("/receive-messages") async def receive_messages(): return {"all_messages": messages}
FastAPI automatically converts JSON messages to Python objects and back.
Use async functions to handle requests efficiently.
Remember to run the FastAPI app with a server like Uvicorn to test endpoints.
FastAPI makes sending and receiving messages easy with simple endpoints.
Use Pydantic models to define message formats clearly.
Store or process messages inside your endpoint functions as needed.
Practice
Solution
Step 1: Understand Pydantic's role in FastAPI
Pydantic models define how data should look, including types and required fields.Step 2: Connect Pydantic to message handling
Using Pydantic ensures messages sent or received follow a clear, expected format.Final Answer:
To clearly define the structure and data types of messages -> Option DQuick Check:
Pydantic models = message structure [OK]
- Confusing Pydantic with HTML templating
- Thinking Pydantic manages databases
- Assuming Pydantic handles authentication
Message?Solution
Step 1: Identify the HTTP method for sending messages
POST is used to send data to the server, so @app.post is correct.Step 2: Check function signature for receiving a Pydantic model
Function must accept a parameter typed as Message to receive the message body.Final Answer:
@app.post('/send')\nasync def send_message(msg: Message):\n return msg -> Option BQuick Check:
POST + typed param = correct endpoint [OK]
- Using GET instead of POST for sending data
- Missing parameter type annotation
- Using wrong HTTP method like PUT
{"text": "Hello"}?
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Message(BaseModel):
text: str
@app.post('/echo')
async def echo_message(msg: Message):
return {"message": msg.text.upper()}Solution
Step 1: Understand the input and model
The input JSON has key "text" with value "Hello", matching Message model.Step 2: Analyze the endpoint return
The function returns a dict with key "message" and value as msg.text.upper(), which converts "Hello" to "HELLO".Final Answer:
{"message": "HELLO"} -> Option AQuick Check:
Uppercase text returned in 'message' key [OK]
- Returning original text without uppercasing
- Returning wrong key name in response
- Expecting an error instead of valid response
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Message(BaseModel):
content: str
@app.post('/receive')
def receive_message(msg: Message):
return {"received": msg.content}Solution
Step 1: Check function declaration for FastAPI async support
FastAPI supports async endpoints; missing async can cause blocking or warnings.Step 2: Verify parameter and decorator correctness
Parameter is correctly typed as Message; @app.post is correct for receiving data.Final Answer:
The endpoint function is missing async keyword -> Option AQuick Check:
Async keyword needed for async endpoints [OK]
- Using sync def without async in async context
- Wrong HTTP method decorator
- Incorrect parameter type annotation
text field, and returns a list of all texts in uppercase. Which code snippet correctly implements this?Solution
Step 1: Use List[Message] to receive multiple messages
Typing msgs as List[Message] allows FastAPI to parse a list of message objects.Step 2: Return uppercase texts from each message
List comprehension extracts each msg.text and converts it to uppercase correctly.Final Answer:
Code snippet with List[Message] parameter and async POST endpoint -> Option CQuick Check:
List of Message + async POST + uppercase list [OK]
- Using single Message instead of list
- Using GET instead of POST for sending data
- Typing list as List[str] instead of List[Message]
Ready to prove it?
Pass the test and this pattern moves unknown
