Bird
Raised Fist0
FastAPIframework~20 mins

WebSocket endpoint creation in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
WebSocket Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when a client sends 'hello' to this WebSocket endpoint?
Consider this FastAPI WebSocket endpoint code. What will the client receive after sending the message 'hello'?
FastAPI
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    data = await websocket.receive_text()
    await websocket.send_text(f'Message received: {data}')
    await websocket.close()
ARuntimeError due to missing await
B"hello"
C"Message received: hello"
DConnection closed without response
Attempts:
2 left
💡 Hint
Look at what the server sends back after receiving the message.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a FastAPI WebSocket endpoint?
Select the option that correctly defines a WebSocket endpoint in FastAPI without syntax errors.
A
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket('/chat')
async def chat(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_text('Welcome!')
B
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket('/chat')
def chat(websocket: WebSocket):
    websocket.accept()
    websocket.send_text('Welcome!')
C
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket('/chat')
async def chat():
    await websocket.accept()
    await websocket.send_text('Welcome!')
D
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket('/chat')
async def chat(websocket):
    await websocket.accept()
    await websocket.send_text('Welcome!')
Attempts:
2 left
💡 Hint
Check for async keyword and parameter type.
❓ state_output
advanced
2:00remaining
What is the value of 'count' after 3 messages are received in this WebSocket endpoint?
Given this WebSocket endpoint, what will be the value of 'count' after the client sends 3 messages?
FastAPI
from fastapi import FastAPI, WebSocket

app = FastAPI()

count = 0

@app.websocket('/counter')
async def counter(websocket: WebSocket):
    global count
    await websocket.accept()
    for _ in range(3):
        await websocket.receive_text()
        count += 1
    await websocket.send_text(f'Count is {count}')
    await websocket.close()
ARaises UnboundLocalError
B0
C1
D3
Attempts:
2 left
💡 Hint
Look at how 'count' is updated inside the loop.
🔧 Debug
advanced
2:00remaining
Which option correctly describes the behavior when connecting to this WebSocket endpoint?
Identify which option correctly describes the behavior when a client connects to this WebSocket endpoint.
FastAPI
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket('/echo')
async def echo(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(data)
AClient connects but server never accepts connection.
BClient sends 'test' and receives 'test' back repeatedly.
CClient connects and server closes connection immediately.
DClient connects and server raises RuntimeError due to missing await.
Attempts:
2 left
💡 Hint
Check if the server accepts connection and awaits properly.
🧠 Conceptual
expert
2:00remaining
What happens if you omit 'await websocket.accept()' in a FastAPI WebSocket endpoint?
In FastAPI, what is the effect of not calling 'await websocket.accept()' inside a WebSocket endpoint function?
AThe client connection is rejected and the handshake fails.
BThe server accepts the connection automatically without explicit accept call.
CThe server sends a default welcome message to the client.
DThe server raises a SyntaxError at runtime.
Attempts:
2 left
💡 Hint
Think about the WebSocket handshake process.

Practice

(1/5)
1. What decorator is used in FastAPI to create a WebSocket endpoint?
easy
A. @app.websocket
B. @app.get
C. @app.post
D. @app.route

Solution

  1. Step 1: Understand FastAPI endpoint decorators

    FastAPI uses different decorators for different endpoint types: @app.get for GET HTTP, @app.post for POST HTTP, and @app.websocket for WebSocket connections.
  2. Step 2: Identify the correct decorator for WebSocket

    Since WebSocket is a different protocol from HTTP, FastAPI uses @app.websocket to create WebSocket endpoints.
  3. Final Answer:

    @app.websocket -> Option A
  4. Quick Check:

    WebSocket endpoint decorator = @app.websocket [OK]
Hint: WebSocket endpoints use @app.websocket decorator [OK]
Common Mistakes:
  • Using @app.get or @app.post instead of @app.websocket
  • Confusing HTTP routes with WebSocket routes
  • Trying to use @app.route which is not in FastAPI
2. Which of the following is the correct syntax to accept a WebSocket connection in FastAPI?
easy
A. await websocket.connect()
B. websocket.accept()
C. await websocket.accept()
D. websocket.connect()

Solution

  1. Step 1: Recognize asynchronous WebSocket methods

    FastAPI WebSocket methods are async, so you must use await to call them.
  2. Step 2: Identify the method to accept a connection

    The method to accept a WebSocket connection is accept(), which must be awaited as await websocket.accept().
  3. Final Answer:

    await websocket.accept() -> Option C
  4. Quick Check:

    Accept WebSocket connection = await websocket.accept() [OK]
Hint: Use await with websocket.accept() to accept connection [OK]
Common Mistakes:
  • Forgetting to use await with async methods
  • Using websocket.connect() which does not exist
  • Calling accept() without await causing runtime errors
3. Given this FastAPI WebSocket endpoint code, what will it send back to the client when the client sends 'hello'?
from fastapi import FastAPI, WebSocket
app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    data = await websocket.receive_text()
    await websocket.send_text(f"Message text was: {data}")
medium
A. Message text was: hello
B. hello
C. Message text was: None
D. Error: receive_text() not awaited

Solution

  1. Step 1: Trace the WebSocket message flow

    The server accepts the connection, then waits to receive text from the client. It stores the received text in 'data'.
  2. Step 2: Understand the response sent back

    The server sends back a message with the text 'Message text was: ' plus the received data. If client sends 'hello', the response is 'Message text was: hello'.
  3. Final Answer:

    Message text was: hello -> Option A
  4. Quick Check:

    Sent message = 'Message text was: hello' [OK]
Hint: Server echoes with prefix 'Message text was:' [OK]
Common Mistakes:
  • Confusing received message with sent message
  • Missing await causing runtime errors
  • Assuming server sends back raw client message without prefix
4. Identify the error in this FastAPI WebSocket endpoint code:
from fastapi import FastAPI, WebSocket
app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    websocket.accept()
    data = await websocket.receive_text()
    await websocket.send_text(data)
medium
A. Missing await before websocket.receive_text()
B. Missing await before websocket.accept()
C. Missing await before websocket.send_text()
D. Incorrect WebSocket path

Solution

  1. Step 1: Check async method calls

    In FastAPI, websocket.accept() is an async method and must be awaited.
  2. Step 2: Identify missing await

    The code calls websocket.accept() without await, which will cause a runtime error.
  3. Final Answer:

    Missing await before websocket.accept() -> Option B
  4. Quick Check:

    Async methods require await = missing await [OK]
Hint: Always await async WebSocket methods like accept() [OK]
Common Mistakes:
  • Calling async methods without await
  • Confusing which methods are async
  • Assuming accept() is synchronous
5. You want to create a FastAPI WebSocket endpoint that continuously receives messages and sends back each message reversed. Which code snippet correctly implements this behavior?
hard
A. async def websocket_endpoint(websocket: WebSocket): websocket.accept() while True: data = websocket.receive_text() websocket.send_text(data[::-1])
B. async def websocket_endpoint(websocket: WebSocket): await websocket.accept() data = await websocket.receive_text() await websocket.send_text(data[::-1])
C. async def websocket_endpoint(websocket: WebSocket): await websocket.accept() for data in websocket.receive_text(): await websocket.send_text(data[::-1])
D. async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(data[::-1])

Solution

  1. Step 1: Understand continuous message handling

    To handle multiple messages, the server must loop indefinitely, receiving and sending messages repeatedly.
  2. Step 2: Check async calls and loop structure

    async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(data[::-1]) uses an async while True loop, awaits receive_text(), and sends back reversed text with await send_text(), correctly handling async and continuous flow.
  3. Final Answer:

    async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(data[::-1]) -> Option D
  4. Quick Check:

    Continuous async loop with await calls = async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(data[::-1]) [OK]
Hint: Use while True with await receive and send for continuous WebSocket [OK]
Common Mistakes:
  • Missing loop for continuous messages
  • Not awaiting async methods
  • Using for loop incorrectly on async receive_text()
  • Calling async methods without await
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