📖 Scenario: You are building a FastAPI application that fetches data from an external API asynchronously. This helps your app stay fast and responsive, even when waiting for other servers.
🎯 Goal: Create a FastAPI app that uses an async HTTP client to get JSON data from a public API and returns it to the user.
📋 What You'll Learn
Use FastAPI to create a web server
Use the httpx.AsyncClient to make asynchronous HTTP GET requests
Create an endpoint /joke that fetches a random joke from the external API
Return the JSON response from the external API directly to the client
💡 Why This Matters
🌍 Real World
Many web apps need to get data from other servers without freezing or slowing down. Async HTTP clients let your app stay fast and handle many users at once.
💼 Career
Knowing how to use async HTTP calls in FastAPI is important for backend developers building scalable APIs and microservices.
Progress0 / 4 steps
1
Set up FastAPI app and import httpx
Create a FastAPI app by importing FastAPI and httpx. Then create an instance called app.
FastAPI
Hint
Use app = FastAPI() to create the app instance.
2
Define the external API URL
Create a variable called joke_api_url and set it to the string "https://official-joke-api.appspot.com/random_joke".
FastAPI
Hint
Assign the URL string exactly to joke_api_url.
3
Create async endpoint to fetch joke
Define an async function called get_joke with the route decorator @app.get("/joke"). Inside, use async with httpx.AsyncClient() as client to make a GET request to joke_api_url. Await the response and return response.json().
FastAPI
Hint
Remember to use async def and await for the HTTP call.
4
Add main guard to run app with Uvicorn
Add the code block if __name__ == "__main__": and inside it call import uvicorn and then uvicorn.run(app, host="127.0.0.1", port=8000) to run the FastAPI app.
FastAPI
Hint
This lets you run the app by executing the script directly.
Practice
(1/5)
1. What is the main benefit of using async HTTP client calls in a FastAPI application?
easy
A. They allow the app to handle other tasks while waiting for the HTTP response.
B. They make the HTTP response faster from the server side.
C. They automatically cache all HTTP responses.
D. They convert HTTP calls into database queries.
Solution
Step 1: Understand async behavior in FastAPI
Async calls let the app continue working without waiting for the HTTP response, improving responsiveness.
Step 2: Identify the benefit of async HTTP client calls
This means the app can handle other requests or tasks while waiting, making it efficient.
Final Answer:
They allow the app to handle other tasks while waiting for the HTTP response. -> Option A
Quick Check:
Async calls improve responsiveness = B [OK]
Hint: Async means non-blocking wait for HTTP response [OK]
Common Mistakes:
Thinking async makes server response faster
Confusing async with caching
Believing async converts HTTP to database calls
2. Which of the following is the correct way to create an async HTTP client call using httpx in FastAPI?
easy
A. async with httpx.AsyncClient() as client: response = await client.get('https://example.com')
B. response = httpx.get('https://example.com')
C. client = httpx.Client(); response = client.get('https://example.com')
D. client = httpx.AsyncClient(); response = client.get('https://example.com')
Solution
Step 1: Identify async client usage
Using async with ensures proper resource management for async clients.
Step 2: Use await to wait for the async HTTP call
The call to client.get() must be awaited to get the response asynchronously.
Final Answer:
async with httpx.AsyncClient() as client: response = await client.get('https://example.com') -> Option A
Quick Check:
Use async with and await for async calls = C [OK]
Hint: Use async with and await for async HTTP calls [OK]
Common Mistakes:
Using httpx.Client instead of AsyncClient for async calls
Not using await with async client.get()
Not using async with for client context
3. What will be the output of this FastAPI async function when called?
import httpx
from fastapi import FastAPI
app = FastAPI()
@app.get('/data')
async def get_data():
async with httpx.AsyncClient() as client:
response = await client.get('https://httpbin.org/get')
return {'status_code': response.status_code}
medium
A. SyntaxError in async function
B. {'status_code': '200'}
C. RuntimeError due to missing await
D. {'status_code': 200}
Solution
Step 1: Analyze the async HTTP call
The function uses await with client.get(), so it correctly waits for the response.
Step 2: Check the returned data
The response status code is an integer 200 for a successful HTTP GET, returned inside a dictionary.
Final Answer:
{'status_code': 200} -> Option D
Quick Check:
Awaited async call returns status 200 = A [OK]
Hint: Await async calls to get response object correctly [OK]
Common Mistakes:
Returning status code as string instead of int
Forgetting await causing runtime errors
Syntax errors from incorrect async usage
4. Identify the error in this FastAPI async HTTP client code:
The client.get() is an async method and must be awaited to get the response.
Step 2: Identify missing await
Without await, the code returns a coroutine object, causing errors when accessing status_code.
Final Answer:
Missing await before client.get() call -> Option B
Quick Check:
Async calls require await = A [OK]
Hint: Always await async client.get() calls [OK]
Common Mistakes:
Not awaiting async HTTP calls
Using sync client in async function
Forgetting async keyword on function
5. You want to fetch data from two different URLs concurrently in a FastAPI async endpoint. Which code correctly achieves this using httpx.AsyncClient?
hard
A. async with httpx.AsyncClient() as client:
r1 = await client.get(url1)
r2 = await client.get(url2)
return {'r1': r1.status_code, 'r2': r2.status_code}
B. async with httpx.AsyncClient() as client:
r1, r2 = await client.get(url1), await client.get(url2)
return {'r1': r1.status_code, 'r2': r2.status_code}
C. async with httpx.AsyncClient() as client:
import asyncio
r1, r2 = await asyncio.gather(client.get(url1), client.get(url2))
return {'r1': r1.status_code, 'r2': r2.status_code}