with python httpx, how to type response ?
- User
with python httpx, how to type response ?
- Assistant
with python httpx, how to type response ?
When using the httpx library in Python, you can assign and work with type annotations for response objects to clarify and maintain the type information in your code. Here's how you can type the response from an HTTP request made using httpx.
First, ensure you have httpx installed:
pip install httpx
Below is an example of how you might use type annotations with an HTTPX response:
Default JSON Response:
If you're dealing with a JSON response, you can make use of httpx.Response and Dict from the typing library:
from typing import Dict
import httpx
def fetch_data(url: str) -> Dict:
response: httpx.Response = httpx.get(url)
response.raise_for_status() # Ensure we raise an error for bad responses
return response.json()
# Example Usage
if __name__ == "__main__":
url = "https://api.example.com/data"
data = fetch_data(url)
print(data)
Handling Different Response Types:
Normally, you might not always expect a JSON response. Here’s how you handle different response objects:
from typing import Union, Any
import httpx
def fetch_data(url: str) -> Union[Dict[str, Any], str, bytes]:
response: httpx.Response = httpx.get(url)
response.raise_for_status() # Check for HTTP errors
# Handle JSON response
if response.headers.get("Content-Type") == "application/json":
return response.json()
# Handle text response
elif response.headers.get("Content-Type").startswith("text/"):
return response.text
# Handle binary response
else:
return response.content
# Example Usage
if __name__ == "__main__":
url = "https://api.example.com/data"
data = fetch_data(url)
print(data)
Custom Response Object:
Sometimes you might use a custom data class for better structure:
from typing import Dict, List, Union
from dataclasses import dataclass
import httpx
@dataclass
class ApiResponse:
status: int
data: Union[List[Dict], Dict]
def fetch_data(url: str) -> ApiResponse:
response: httpx.Response = httpx.get(url)
response.raise_for_status()
# Assuming the response is JSON
data = response.json()
return ApiResponse(status=response.status_code, data=data)
# Example Usage
if __name__ == "__main__":
url = "https://api.example.com/data"
api_response = fetch_data(url)
print(api_response)
By using these type annotations and handling various response types appropriately, you can maintain clarity and robustness in your HTTP request handling with httpx in Python.
Not yet included in a published release.