response = httpx . get ( " https://jsonplaceholder.typicode.com/posts/1 " ) print ( response . status_code ) # 200 print ( response . json ()) # 解析 JSON 回應
data = {"title": "Hello", "body": "World", "userId": 1}
response = httpx.post("https://jsonplaceholder.typicode.com/posts", json=data)
print(response.status_code)  # 201(代表成功建立資源)
print(response.json())  # 解析回應內容

requests 一樣, httpx 支援 json= 參數來發送 JSON 格式的資料。

# 建立一個 HTTP 會話 with httpx . Client () as client : response = client . get ( " https://jsonplaceholder.typicode.com/posts/1 " ) print ( response . json ()) # 輸出 API 回應 # 建立 HTTP 會話 with httpx . Client () as client : response1 = client . get ( " https://jsonplaceholder.typicode.com/posts/1 " ) response2 = client . get ( " https://jsonplaceholder.typicode.com/posts/2 " ) response3 = client . get ( " https://jsonplaceholder.typicode.com/posts/3 " ) print ( response1 . json ()) print ( response2 . json ()) print ( response3 . json ()) response1 = httpx . get ( " https://jsonplaceholder.typicode.com/posts/1 " ) response2 = httpx . get ( " https://jsonplaceholder.typicode.com/posts/2 " ) response3 = httpx . get ( " https://jsonplaceholder.typicode.com/posts/3 " ) async def fetch (): async with httpx . AsyncClient () as client : response = await client . get ( " https://jsonplaceholder.typicode.com/posts/1 " ) print ( response . json ()) # 輸出 API 回應 # 使用 asyncio.run() 來執行異步函式 asyncio . run ( fetch ()) async def fetch ( url ): async with httpx . AsyncClient () as client : response = await client . get ( url ) return response . json () # 回傳 JSON 結果 async def main (): urls = [ " https://jsonplaceholder.typicode.com/posts/1 " , " https://jsonplaceholder.typicode.com/posts/2 " , " https://jsonplaceholder.typicode.com/posts/3 " , # 建立多個異步任務 tasks = [ fetch ( url ) for url in urls ] # 使用 asyncio.gather() 來同時執行所有請求 results = await asyncio . gather (* tasks ) print ( results ) # 輸出所有請求結果 # 執行異步請求 asyncio . run ( main ())