Bird
Raised Fist0
FastAPIframework~20 mins

ASGI and async-first architecture in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ASGI Async Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
1:30remaining
What is the output of this FastAPI async endpoint?
Consider this FastAPI endpoint using async def. What will the client receive when calling /hello?
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get('/hello')
async def hello():
    return {'message': 'Hello, async world!'}
A{"message": "Hello, async world!"}
BHello, async world!
CAn error because async functions cannot return dict
DA JSON string with key 'hello' and value 'world'
Attempts:
2 left
💡 Hint
Remember that FastAPI automatically converts dict returns to JSON responses.
❓ lifecycle
intermediate
1:30remaining
What happens when an async FastAPI endpoint awaits a slow function?
Given this code, what is the behavior when a client calls /wait?
from fastapi import FastAPI
import asyncio
app = FastAPI()

@app.get('/wait')
async def wait():
    await asyncio.sleep(2)
    return {'status': 'done'}
AThe server blocks all other requests for 2 seconds before responding
BThe client receives an immediate empty response, then the final response after 2 seconds
CThe server crashes because asyncio.sleep cannot be awaited
DThe server handles other requests during the 2 seconds wait asynchronously
Attempts:
2 left
💡 Hint
Think about how async functions allow other tasks to run while waiting.
📝 Syntax
advanced
2:00remaining
Which option will cause a syntax error in this async FastAPI endpoint?
Identify the option that will cause a syntax error when defining an async FastAPI endpoint.
FastAPI
from fastapi import FastAPI
app = FastAPI()
A
@app.get('/test')
def test():
    await some_async_func()
    return {'msg': 'ok'}
B
@app.get('/test')
async def test():
    return {'msg': 'ok'}
C
@app.get('/test')
async def test():
    await some_async_func()
    return {'msg': 'ok'}
D
}'ko' :'gsm'{ nruter    
:)(tset fed cnysa
)'tset/'(teg.ppa@
Attempts:
2 left
💡 Hint
Remember that 'await' can only be used inside async functions.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI async endpoint raise a RuntimeError?
Examine this code snippet. Why does calling /error raise a RuntimeError?
from fastapi import FastAPI
import asyncio
app = FastAPI()

@app.get('/error')
def error():
    asyncio.create_task(asyncio.sleep(1))
    return {'status': 'started'}
ABecause asyncio.sleep cannot be used in FastAPI endpoints
BBecause asyncio.create_task must be called inside an async function
CBecause the endpoint is missing an await keyword
DBecause FastAPI does not support background tasks
Attempts:
2 left
💡 Hint
Check where asyncio.create_task is allowed to run.
🧠 Conceptual
expert
2:30remaining
What is the main advantage of ASGI over WSGI in FastAPI's async-first architecture?
Choose the best explanation for why FastAPI uses ASGI instead of WSGI.
AASGI only supports synchronous code which improves stability
BASGI is simpler to implement and requires less code than WSGI
CASGI supports asynchronous concurrency allowing multiple requests to be handled simultaneously without blocking
DASGI automatically caches all responses to speed up the server
Attempts:
2 left
💡 Hint
Think about how async code benefits server concurrency.

Practice

(1/5)
1. What does ASGI enable FastAPI to do compared to traditional synchronous frameworks?
easy
A. Use only synchronous functions for better speed
B. Run only one request at a time to avoid conflicts
C. Handle many requests at the same time using async code
D. Automatically convert Python code to JavaScript

Solution

  1. Step 1: Understand ASGI's role

    ASGI is designed to handle multiple requests concurrently using asynchronous programming.
  2. Step 2: Compare with synchronous frameworks

    Traditional synchronous frameworks handle one request at a time, blocking others until done.
  3. Final Answer:

    Handle many requests at the same time using async code -> Option C
  4. Quick Check:

    ASGI = concurrent async handling [OK]
Hint: ASGI means multitasking with async code [OK]
Common Mistakes:
  • Thinking ASGI runs requests one by one
  • Confusing ASGI with code conversion tools
  • Believing async slows down the app
2. Which of the following is the correct way to define an async route handler in FastAPI?
easy
A. async def read_root(): return {"message": "Hello"}
B. def read_root(): return {"message": "Hello"}
C. async read_root(): return {"message": "Hello"}
D. def async read_root(): return {"message": "Hello"}

Solution

  1. Step 1: Recall async function syntax

    In Python, async functions start with async def followed by the function name.
  2. Step 2: Check each option's syntax

    async def read_root(): return {"message": "Hello"} correctly uses async def. Options C and D have invalid syntax. def read_root(): return {"message": "Hello"} is synchronous.
  3. Final Answer:

    async def read_root(): return {"message": "Hello"} -> Option A
  4. Quick Check:

    Async function = async def [OK]
Hint: Async functions start with 'async def' [OK]
Common Mistakes:
  • Omitting 'def' after 'async'
  • Placing 'async' after 'def'
  • Using synchronous 'def' for async routes
3. Given this FastAPI route handler, what will be the output when accessed?
from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.get("/wait")
async def wait_and_return():
    await asyncio.sleep(1)
    return {"status": "done"}
medium
A. Error because asyncio.sleep cannot be awaited
B. Immediate response with {"status": "done"}
C. Server crashes due to blocking call
D. {"status": "done"} after 1 second delay

Solution

  1. Step 1: Understand async sleep behavior

    The function uses await asyncio.sleep(1), which pauses the function asynchronously for 1 second.
  2. Step 2: Predict response timing

    The response will be sent after the 1 second delay, returning the JSON with status done.
  3. Final Answer:

    {"status": "done"} after 1 second delay -> Option D
  4. Quick Check:

    Await asyncio.sleep = delayed async response [OK]
Hint: Await asyncio.sleep delays response asynchronously [OK]
Common Mistakes:
  • Thinking await asyncio.sleep blocks all requests
  • Expecting immediate response ignoring await
  • Confusing asyncio.sleep with time.sleep
4. Identify the error in this FastAPI async route handler:
from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.get("/error")
def error_route():
    await asyncio.sleep(1)
    return {"message": "done"}
medium
A. Missing async keyword before function definition
B. Cannot use await inside async function
C. FastAPI does not support async routes
D. Return statement must be inside try-except block

Solution

  1. Step 1: Check function definition

    The function uses await but is defined without async, which is invalid syntax.
  2. Step 2: Understand async function requirements

    To use await, the function must be declared with async def.
  3. Final Answer:

    Missing async keyword before function definition -> Option A
  4. Quick Check:

    Await requires async def [OK]
Hint: Use async def when using await inside function [OK]
Common Mistakes:
  • Forgetting async before def
  • Thinking await works in sync functions
  • Believing FastAPI disallows async routes
5. You want to create a FastAPI endpoint that fetches data from two slow APIs concurrently to improve speed. Which approach best uses FastAPI's async-first architecture?
hard
A. Use async functions with await on both API calls sequentially
B. Use asyncio.gather to run both async API calls concurrently inside an async route
C. Call both APIs one after another using synchronous requests inside an async function
D. Run synchronous API calls in separate threads without async

Solution

  1. Step 1: Understand concurrency with async

    Calling APIs sequentially with await waits for each to finish before starting the next, not concurrent.
  2. Step 2: Use asyncio.gather for concurrency

    asyncio.gather runs multiple async tasks at the same time, improving speed.
  3. Step 3: Compare options

    Use asyncio.gather to run both async API calls concurrently inside an async route uses asyncio.gather inside async route, best leveraging FastAPI's async-first design.
  4. Final Answer:

    Use asyncio.gather to run both async API calls concurrently inside an async route -> Option B
  5. Quick Check:

    asyncio.gather = concurrent async calls [OK]
Hint: Use asyncio.gather for concurrent async calls [OK]
Common Mistakes:
  • Awaiting calls sequentially losing concurrency
  • Using synchronous calls blocking event loop
  • Ignoring async and threading differences
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