-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtesthttpx.py
More file actions
43 lines (33 loc) · 997 Bytes
/
Copy pathtesthttpx.py
File metadata and controls
43 lines (33 loc) · 997 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import asyncio
from dataclasses import dataclass
from pydantic import BaseModel,Field
import json
import httpx
# response=httpx.get("https://jsonplaceholder.typicode.com/posts/1")
# print(response.status_code)
# print(response.json())
class Post(BaseModel):
user_id: int = Field(alias="userId")
id: int
title: str
body: str
async def fetch() -> Post:
try:
async with httpx.AsyncClient() as client:
response = await client.get("https://jsonplaceholder.typicode.com/posts/1")
response.raise_for_status()
data = response.json()
p = Post.model_validate(data)
# print(p.title)
# print(p.id)
return p
except httpx.HTTPError as exc:
print(f"HTTP request failed: {exc}")
raise
except ValueError as exc:
print(f"Failed to parse response payload: {exc}")
raise
async def main():
p = await fetch()
print(p)
asyncio.run(main())