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?
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()
Think about what response.json() returns after awaiting the HTTP GET request.
The httpx.AsyncClient fetches JSON data from the external API. Awaiting the client.get call returns a response object. Calling response.json() returns the parsed JSON dictionary. So the endpoint returns a JSON dictionary with keys like 'args', 'headers', 'origin', and 'url'.
Which code snippet correctly performs an asynchronous HTTP GET request inside a FastAPI endpoint using httpx.AsyncClient?
Remember to await async calls and use async context managers properly.
Option B correctly uses async with to create the client and await to wait for the HTTP GET request. Option B misses await, so it returns a coroutine. Option B uses a synchronous context manager which is invalid for async client. Option B misses the async context manager, which can cause resource leaks.
Given this FastAPI endpoint, why does it raise a RuntimeError: Cannot run the event loop while another loop is running?
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())
Think about how FastAPI runs async endpoints and event loops.
FastAPI runs on an async event loop. Calling asyncio.run() inside an already running event loop causes a RuntimeError. Instead, the endpoint itself should be async and await the async calls directly.
In this async function, what will be the value of result after execution?
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())
Check the HTTP status code returned by the URL.
The URL https://httpbin.org/status/204 returns HTTP status code 204 (No Content). The response.status_code will be 204, which is returned and assigned to result.
Choose the correct statement about using async HTTP clients like httpx.AsyncClient in FastAPI applications.
Think about how async calls help with concurrency in web servers.
Async HTTP clients like httpx.AsyncClient allow FastAPI endpoints to perform HTTP requests without blocking the event loop. This improves concurrency and scalability. Running multiple workers is unrelated to async client usage. Async clients do not cache responses automatically. FastAPI endpoints should be async to use async clients properly.