0
0
FastAPIframework~10 mins

Async HTTP client calls in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the async HTTP client from httpx.

FastAPI
from [1] import AsyncClient
Drag options to blanks, or click blank then click option'
Aasyncio
Brequests
Cfastapi
Dhttpx
Attempts:
3 left
💡 Hint
Common Mistakes
Importing AsyncClient from requests instead of httpx.
Trying to import AsyncClient from fastapi.
2fill in blank
medium

Complete the code to create an async function that makes a GET request using AsyncClient.

FastAPI
async def fetch_data(url: str):
    async with AsyncClient() as client:
        response = await client.[1](url)
        return response.text
Drag options to blanks, or click blank then click option'
Apost
Bput
Cget
Ddelete
Attempts:
3 left
💡 Hint
Common Mistakes
Using post instead of get for fetching data.
Forgetting to await the async call.
3fill in blank
hard

Fix the error in the async function to correctly return JSON data from the response.

FastAPI
async def fetch_json(url: str):
    async with AsyncClient() as client:
        response = await client.get(url)
        data = await response.[1]()
        return data
Drag options to blanks, or click blank then click option'
Atext
Bjson
Ccontent
Dread
Attempts:
3 left
💡 Hint
Common Mistakes
Using response.text() which returns a string, not parsed JSON.
Using response.content() which returns bytes.
4fill in blank
hard

Fill both blanks to create a FastAPI route that calls the async fetch_data function and returns the result.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.[1]("/data")
async def get_data():
    result = await fetch_data([2])
    return {"data": result}
Drag options to blanks, or click blank then click option'
Aget
B"https://example.com/api"
C"/fetch"
Dpost
Attempts:
3 left
💡 Hint
Common Mistakes
Using @app.post instead of @app.get for a GET route.
Passing a variable name instead of a URL string to fetch_data.
5fill in blank
hard

Fill all three blanks to create an async function that posts JSON data and returns the JSON response.

FastAPI
async def post_json(url: str, payload: dict):
    async with AsyncClient() as client:
        response = await client.[1](url, json=[2])
        return await response.[3]()
Drag options to blanks, or click blank then click option'
Apost
Bpayload
Cjson
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using get instead of post for sending data.
Passing payload as a positional argument instead of json keyword.
Using response.text() instead of response.json() to parse JSON.