📖 Scenario: You are building a simple web API using FastAPI. You want to understand how using asynchronous functions can help your API handle more requests efficiently.
🎯 Goal: Create a FastAPI app with a synchronous endpoint and an asynchronous endpoint. Learn how async functions improve performance by not blocking the server while waiting for slow tasks.
📋 What You'll Learn
Create a FastAPI app instance called app
Define a synchronous endpoint /sync that simulates a slow task using time.sleep(2)
Define an asynchronous endpoint /async that simulates a slow task using await asyncio.sleep(2)
Run the FastAPI app and observe how async endpoint allows handling multiple requests concurrently
💡 Why This Matters
🌍 Real World
Web APIs often need to handle many users at once. Using async lets the server work on other requests while waiting for slow tasks like database queries or network calls.
💼 Career
Understanding async in FastAPI is important for backend developers to build fast, scalable web services that can handle many users efficiently.
Progress0 / 4 steps
1
Create FastAPI app and synchronous endpoint
Import FastAPI and time. Create a FastAPI app instance called app. Define a synchronous GET endpoint /sync that waits 2 seconds using time.sleep(2) and returns the text 'Synchronous response'.
FastAPI
Hint
Use @app.get('/sync') decorator and define a normal function that calls time.sleep(2).
2
Add async endpoint configuration
Import asyncio. Define an asynchronous GET endpoint /async using async def that waits 2 seconds using await asyncio.sleep(2) and returns the text 'Asynchronous response'.
FastAPI
Hint
Use async def and await asyncio.sleep(2) inside the async endpoint function.
3
Explain async performance benefit with example
Add a comment above the async endpoint explaining that async allows the server to handle other requests while waiting. Also add a comment above the sync endpoint explaining it blocks the server during the wait.
FastAPI
Hint
Write clear comments above each endpoint explaining blocking vs non-blocking behavior.
4
Add code to run FastAPI app with uvicorn
Add the code to run the FastAPI app using uvicorn.run with app as the app instance, host as '127.0.0.1', and port 8000. Use the if __name__ == '__main__' guard.
FastAPI
Hint
Use if __name__ == '__main__': and call uvicorn.run with the correct parameters.
Practice
(1/5)
1. Why does using async functions in FastAPI improve performance?
easy
A. Because async lets the app handle other tasks while waiting for slow operations
B. Because async makes the code run faster by using more CPU power
C. Because async removes the need for a web server
D. Because async automatically caches all responses
Solution
Step 1: Understand what async does in FastAPI
Async functions allow the app to pause waiting for slow tasks like database calls without blocking other requests.
Step 2: Connect async behavior to performance improvement
This means the app can handle multiple requests at once, improving speed and user experience.
Final Answer:
Because async lets the app handle other tasks while waiting for slow operations -> Option A
Quick Check:
Async improves concurrency = C [OK]
Hint: Async means do other work while waiting [OK]
Common Mistakes:
Thinking async makes code run faster on CPU
Believing async removes the need for a server
Assuming async caches responses automatically
2. Which is the correct way to define an async endpoint in FastAPI?
easy
A. def get_data():
B. async def get_data():
C. await def get_data():
D. async get_data():
Solution
Step 1: Recall Python async function syntax
Async functions are defined with the keyword async def before the function name.
Step 2: Match syntax to FastAPI endpoint definition
FastAPI supports async endpoints by using async def to allow await inside the function.
Final Answer:
async def get_data(): -> Option B
Quick Check:
Async function syntax = B [OK]
Hint: Async functions start with 'async def' [OK]
Common Mistakes:
Using 'await def' which is invalid syntax
Omitting 'async' keyword for async endpoints
Writing 'async get_data()' without 'def'
3. What will happen if a FastAPI async endpoint awaits a slow database call?
medium
A. The server can handle other requests while waiting for the database
B. The server ignores the database call
C. The server crashes due to blocking
D. The server blocks and cannot handle other requests until done
Solution
Step 1: Understand await in async functions
When an async function awaits a slow operation, it pauses that task but frees the server to do other work.
Step 2: Apply this to FastAPI server behavior
FastAPI can process other incoming requests during this wait, improving throughput.
Final Answer:
The server can handle other requests while waiting for the database -> Option A
Quick Check:
Await frees server to handle others = D [OK]
Hint: Await pauses task but frees server for others [OK]
Common Mistakes:
Thinking await blocks the whole server
Assuming server crashes on await
Believing await skips the database call
4. Identify the error in this FastAPI async endpoint code:
from fastapi import FastAPI
app = FastAPI()
@app.get('/items')
def read_items():
data = await fetch_data()
return data
medium
A. Missing FastAPI import
B. Missing await keyword before fetch_data()
C. Using def instead of function name
D. Missing async keyword before function definition
Solution
Step 1: Check function definition for async keyword
The function uses await inside but is defined with def instead of async def, which is invalid.
Step 2: Understand await requires async function
Await can only be used inside async functions, so the function must be async def.
Final Answer:
Missing async keyword before function definition -> Option D
Quick Check:
Await needs async def = A [OK]
Hint: Await only works inside async def functions [OK]
Common Mistakes:
Forgetting async before def when using await
Thinking await is optional inside async
Confusing function name with def keyword
5. You want to improve a FastAPI app that calls two slow APIs sequentially. How does using async improve performance?
hard
A. Async makes the API calls run faster on the server CPU
B. Async caches the API responses automatically
C. Async lets both API calls run at the same time, reducing total wait time
D. Async disables one API call to save time
Solution
Step 1: Understand sequential vs concurrent calls
Calling two slow APIs one after another waits for the first to finish before starting the second.
Step 2: Apply async concurrency to API calls
Using async, both calls can start and wait at the same time, reducing total wait time.
Final Answer:
Async lets both API calls run at the same time, reducing total wait time -> Option C
Quick Check:
Async enables concurrency = A [OK]
Hint: Async runs slow tasks together, not one by one [OK]
Common Mistakes:
Thinking async speeds up CPU processing
Assuming async caches responses automatically
Believing async disables tasks to save time
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.