Bird
Raised Fist0
FastAPIframework~20 mins

Sending and receiving messages in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Message Mastery in FastAPI
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this FastAPI endpoint when sending a POST request?
Consider this FastAPI endpoint that receives a JSON message and returns a confirmation.
What will be the JSON response if the client sends {"message": "Hello"}?
FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.post("/send")
async def send_message(request: Request):
    data = await request.json()
    msg = data.get("message", "")
    return JSONResponse(content={"status": "received", "message": msg})
A{"message": "Hello"}
B{"status": "received"}
C{"status": "received", "message": "Hello"}
D500 Internal Server Error
Attempts:
2 left
💡 Hint
Look at how the endpoint reads the JSON and what it returns in the response.
❓ state_output
intermediate
2:00remaining
What is the value of 'messages' after these requests?
Given this FastAPI app that stores messages in a list, what will be the content of 'messages' after two POST requests with messages "Hi" and "Bye"?
FastAPI
from fastapi import FastAPI, Request

app = FastAPI()
messages = []

@app.post("/chat")
async def chat(request: Request):
    data = await request.json()
    messages.append(data.get("message", ""))
    return {"count": len(messages)}
A["Hi", "Bye"]
B["Bye", "Hi"]
C[]
D["Hi"]
Attempts:
2 left
💡 Hint
The list 'messages' is global and appends each message received.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in this FastAPI message handler?
Identify which code snippet will cause a syntax error when defining a FastAPI POST endpoint that receives JSON.
A
async def receive(request Request):
    data = await request.json()
    return {"msg": data["message"]}
B
async def receive(request: Request):
    data = await request.json()
    return {"msg": data["message"]}
C
async def receive(request: Request):
    data = await request.json()
    return {"msg": data.get("message")}
D
}]"egassem"[atad :"gsm"{ nruter    
)(nosj.tseuqer tiawa = atad    
:)tseuqeR :tseuqer(eviecer fed cnysa
Attempts:
2 left
💡 Hint
Check the function parameter syntax carefully.
🔧 Debug
advanced
2:00remaining
Which option will cause a runtime error when sending a message?
Given these FastAPI endpoints, which one will raise an error when a POST request with JSON {"message": "Hello"} is sent?
A
async def send(request: Request):
    data = await request.json()
    return {"msg": data["message"]}
B
async def send(request: Request):
    data = await request.json()
    return {"msg": data.message}
C
async def send(request: Request):
    data = await request.json()
    return {"msg": data.get("message", "")}
D
async def send(request: Request):
    data = await request.json()
    return {"msg": data.get("message")}
Attempts:
2 left
💡 Hint
Consider how JSON data is accessed in Python dictionaries.
🧠 Conceptual
expert
3:00remaining
What is the correct way to handle concurrent message storage in FastAPI?
You want to store messages received via POST requests in a list safely when multiple clients send messages at the same time. Which approach ensures thread-safe updates?
AUse a global list and rely on FastAPI's single-threaded nature to avoid conflicts.
BUse a global list and append messages directly without locks.
CUse a local list inside the endpoint function to store messages temporarily.
DUse a global list and protect append operations with an asyncio.Lock.
Attempts:
2 left
💡 Hint
Think about concurrency and shared data safety in async web servers.

Practice

(1/5)
1. What is the main purpose of using Pydantic models in FastAPI when sending and receiving messages?
easy
A. To create HTML templates for message display
B. To manage user authentication tokens
C. To handle database connections automatically
D. To clearly define the structure and data types of messages

Solution

  1. Step 1: Understand Pydantic's role in FastAPI

    Pydantic models define how data should look, including types and required fields.
  2. Step 2: Connect Pydantic to message handling

    Using Pydantic ensures messages sent or received follow a clear, expected format.
  3. Final Answer:

    To clearly define the structure and data types of messages -> Option D
  4. Quick Check:

    Pydantic models = message structure [OK]
Hint: Pydantic models describe message shape and types [OK]
Common Mistakes:
  • Confusing Pydantic with HTML templating
  • Thinking Pydantic manages databases
  • Assuming Pydantic handles authentication
2. Which of the following is the correct way to declare a POST endpoint in FastAPI that receives a message model named Message?
easy
A. @app.post('/send')\ndef send_message():\n return Message
B. @app.post('/send')\nasync def send_message(msg: Message):\n return msg
C. @app.get('/send')\nasync def send_message(msg: Message):\n return msg
D. @app.put('/send')\nasync def send_message(msg: Message):\n return msg

Solution

  1. Step 1: Identify the HTTP method for sending messages

    POST is used to send data to the server, so @app.post is correct.
  2. Step 2: Check function signature for receiving a Pydantic model

    Function must accept a parameter typed as Message to receive the message body.
  3. Final Answer:

    @app.post('/send')\nasync def send_message(msg: Message):\n return msg -> Option B
  4. Quick Check:

    POST + typed param = correct endpoint [OK]
Hint: Use @app.post and typed parameter for message body [OK]
Common Mistakes:
  • Using GET instead of POST for sending data
  • Missing parameter type annotation
  • Using wrong HTTP method like PUT
3. Given this FastAPI endpoint code, what will be the response when sending a POST request with JSON {"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()}
medium
A. {"message": "HELLO"}
B. {"message": "Hello"}
C. {"text": "HELLO"}
D. 500 Internal Server Error

Solution

  1. Step 1: Understand the input and model

    The input JSON has key "text" with value "Hello", matching Message model.
  2. 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".
  3. Final Answer:

    {"message": "HELLO"} -> Option A
  4. Quick Check:

    Uppercase text returned in 'message' key [OK]
Hint: Look for .upper() call on input text [OK]
Common Mistakes:
  • Returning original text without uppercasing
  • Returning wrong key name in response
  • Expecting an error instead of valid response
4. What is wrong with this FastAPI endpoint code for receiving a message?
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}
medium
A. The endpoint function is missing async keyword
B. The parameter msg should be annotated with Request
C. The endpoint must use @app.get instead of @app.post
D. The function must return a Pydantic model instance

Solution

  1. Step 1: Check function declaration for FastAPI async support

    FastAPI supports async endpoints; missing async can cause blocking or warnings.
  2. Step 2: Verify parameter and decorator correctness

    Parameter is correctly typed as Message; @app.post is correct for receiving data.
  3. Final Answer:

    The endpoint function is missing async keyword -> Option A
  4. Quick Check:

    Async keyword needed for async endpoints [OK]
Hint: Use async def for FastAPI POST endpoints [OK]
Common Mistakes:
  • Using sync def without async in async context
  • Wrong HTTP method decorator
  • Incorrect parameter type annotation
5. You want to create a FastAPI endpoint that receives a list of messages, each with a text field, and returns a list of all texts in uppercase. Which code snippet correctly implements this?
hard
A. from fastapi import FastAPI from pydantic import BaseModel from typing import List app = FastAPI() class Message(BaseModel): text: str @app.get('/batch') def batch_messages(msgs: List[Message]): return [msg.text.upper() for msg in msgs]
B. from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Message(BaseModel): text: str @app.post('/batch') async def batch_messages(msgs: Message): return [msg.text.upper() for msg in msgs]
C. from fastapi import FastAPI from pydantic import BaseModel from typing import List app = FastAPI() class Message(BaseModel): text: str @app.post('/batch') async def batch_messages(msgs: List[Message]): return [msg.text.upper() for msg in msgs]
D. from fastapi import FastAPI from pydantic import BaseModel from typing import List app = FastAPI() class Message(BaseModel): text: str @app.post('/batch') async def batch_messages(msgs: List[str]): return [text.upper() for text in msgs]

Solution

  1. Step 1: Use List[Message] to receive multiple messages

    Typing msgs as List[Message] allows FastAPI to parse a list of message objects.
  2. Step 2: Return uppercase texts from each message

    List comprehension extracts each msg.text and converts it to uppercase correctly.
  3. Final Answer:

    Code snippet with List[Message] parameter and async POST endpoint -> Option C
  4. Quick Check:

    List of Message + async POST + uppercase list [OK]
Hint: Use List[Message] and async POST for batch message input [OK]
Common Mistakes:
  • Using single Message instead of list
  • Using GET instead of POST for sending data
  • Typing list as List[str] instead of List[Message]
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard