Sezione 1. Capitolo 7
single
Challenge: Your First Async Function
Scorri per mostrare il menu
You are working with the public API jsonplaceholder.typicode.com, which provides fake data for testing and learning. Your task is to fetch user information and display it in a readable format.
The endpoint https://jsonplaceholder.typicode.com/users/{user_id} returns a JSON object with the following fields:
name: the user's full name;email: the user's email address;company: an object with anamefield containing the company name.
Compito
Scorri per iniziare a programmare
- Define an async function
fetch_user(client, user_id)that:- Sends a GET request to the users endpoint using the provided
clientanduser_id; - Extracts
name,email, and companynamefrom the response; - Prints them in the format:
Name | Email | Company.
- Sends a GET request to the users endpoint using the provided
- Define an async function
main()that:- Creates an
httpx.AsyncClient; - Uses
asyncio.gather()to fetch users with IDs1,2, and3concurrently.
- Creates an
- Run
main()usingasyncio.run().
Soluzione
Tutto è chiaro?
Grazie per i tuoi commenti!
Sezione 1. Capitolo 7
single
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione