Avsnitt 1. Kapitel 7
single
Challenge: Your First Async Function
Svep för att visa menyn
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.
Uppgift
Svep för att börja koda
- 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().
Lösning
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 1. Kapitel 7
single
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal