Bird
Raised Fist0
FastAPIframework~20 mins

Async HTTP client calls in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Async HTTP Client Master
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 async client call?

Consider this FastAPI endpoint using httpx.AsyncClient to fetch data from an external API asynchronously. What will be the response content when calling /fetch-data?

FastAPI
from fastapi import FastAPI
import httpx

app = FastAPI()

@app.get('/fetch-data')
async def fetch_data():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://httpbin.org/get')
        return response.json()
AA JSON dictionary with keys like 'args', 'headers', 'origin', and 'url' from httpbin.org
BA plain text string with the raw HTML content of https://httpbin.org/get
CA runtime error because httpx.AsyncClient cannot be used inside FastAPI endpoints
DAn empty JSON object {} because the response is not awaited properly
Attempts:
2 left
💡 Hint

Think about what response.json() returns after awaiting the HTTP GET request.

📝 Syntax
intermediate
2:00remaining
Which option correctly uses async HTTP client in FastAPI?

Which code snippet correctly performs an asynchronous HTTP GET request inside a FastAPI endpoint using httpx.AsyncClient?

A
client = httpx.AsyncClient()
response = await client.get('https://example.com')
return response.text
B
async with httpx.AsyncClient() as client:
    response = await client.get('https://example.com')
    return response.text
C
with httpx.AsyncClient() as client:
    response = await client.get('https://example.com')
    return response.text
D
async with httpx.AsyncClient() as client:
    response = client.get('https://example.com')
    return response.text
Attempts:
2 left
💡 Hint

Remember to await async calls and use async context managers properly.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI async client code raise an error?

Given this FastAPI endpoint, why does it raise a RuntimeError: Cannot run the event loop while another loop is running?

FastAPI
from fastapi import FastAPI
import httpx
import asyncio

app = FastAPI()

@app.get('/data')
def get_data():
    async def fetch():
        async with httpx.AsyncClient() as client:
            response = await client.get('https://httpbin.org/get')
            return response.json()
    return asyncio.run(fetch())
ABecause httpx.AsyncClient() must be used synchronously, not asynchronously
BBecause FastAPI endpoints cannot define inner functions
CBecause the inner async function fetch() is missing the await keyword before client.get()
DBecause asyncio.run() cannot be called inside an already running event loop like FastAPI's async server
Attempts:
2 left
💡 Hint

Think about how FastAPI runs async endpoints and event loops.

❓ state_output
advanced
2:00remaining
What is the value of 'result' after this async HTTP call?

In this async function, what will be the value of result after execution?

FastAPI
import httpx

async def fetch_status():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://httpbin.org/status/204')
        return response.status_code

import asyncio
result = asyncio.run(fetch_status())
A204
B200
CNone
DRaises an HTTPError because 204 is no content
Attempts:
2 left
💡 Hint

Check the HTTP status code returned by the URL.

🧠 Conceptual
expert
2:00remaining
Which statement about async HTTP client calls in FastAPI is TRUE?

Choose the correct statement about using async HTTP clients like httpx.AsyncClient in FastAPI applications.

AAsync HTTP clients automatically cache responses to improve performance without extra code
BUsing <code>httpx.AsyncClient</code> requires running FastAPI with multiple worker processes to enable async behavior
CUsing <code>httpx.AsyncClient</code> inside FastAPI endpoints improves concurrency by not blocking the event loop during HTTP calls
DFastAPI endpoints must be synchronous when using async HTTP clients to avoid runtime errors
Attempts:
2 left
💡 Hint

Think about how async calls help with concurrency in web servers.

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

  1. Step 1: Understand async behavior in FastAPI

    Async calls let the app continue working without waiting for the HTTP response, improving responsiveness.
  2. 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.
  3. Final Answer:

    They allow the app to handle other tasks while waiting for the HTTP response. -> Option A
  4. 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

  1. Step 1: Identify async client usage

    Using async with ensures proper resource management for async clients.
  2. Step 2: Use await to wait for the async HTTP call

    The call to client.get() must be awaited to get the response asynchronously.
  3. Final Answer:

    async with httpx.AsyncClient() as client: response = await client.get('https://example.com') -> Option A
  4. 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

  1. Step 1: Analyze the async HTTP call

    The function uses await with client.get(), so it correctly waits for the response.
  2. Step 2: Check the returned data

    The response status code is an integer 200 for a successful HTTP GET, returned inside a dictionary.
  3. Final Answer:

    {'status_code': 200} -> Option D
  4. 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:
import httpx
from fastapi import FastAPI
app = FastAPI()

@app.get('/info')
async def get_info():
    client = httpx.AsyncClient()
    response = client.get('https://httpbin.org/get')
    return {'status': response.status_code}
medium
A. Using httpx.Client instead of AsyncClient
B. Missing await before client.get() call
C. Missing async keyword in function definition
D. Incorrect return type, should return string

Solution

  1. Step 1: Check async call usage

    The client.get() is an async method and must be awaited to get the response.
  2. Step 2: Identify missing await

    Without await, the code returns a coroutine object, causing errors when accessing status_code.
  3. Final Answer:

    Missing await before client.get() call -> Option B
  4. 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}
D. client = httpx.AsyncClient() r1 = client.get(url1) r2 = client.get(url2) return {'r1': r1.status_code, 'r2': r2.status_code}

Solution

  1. Step 1: Understand concurrency with async HTTP calls

    To run multiple async calls concurrently, use asyncio.gather() to await them together.
  2. Step 2: Check code correctness

    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} uses asyncio.gather() inside async with context, correctly awaiting both calls concurrently.
  3. Final Answer:

    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} -> Option C
  4. Quick Check:

    Use asyncio.gather for concurrent async calls = D [OK]
Hint: Use asyncio.gather to await multiple async calls concurrently [OK]
Common Mistakes:
  • Awaiting calls sequentially losing concurrency
  • Not awaiting calls causing coroutine errors
  • Not using async with for client context
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