Pyton api
- User
Pyton api
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Pyton api
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here are several examples of making API requests in Python using different libraries:
requests library (most popular)import requests
import json
# POST request example
def post_api_example():
url = "https://api.example.com/endpoint"
# Data to send
data = {
"key1": "value1",
"key2": "value2"
}
# Headers
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer your-token-here" # if needed
}
try:
# Make POST request
response = requests.post(url, json=data, headers=headers)
# Check if request was successful
response.raise_for_status()
# Print response
print(f"Status Code: {response.status_code}")
print(f"Response: {response.json()}")
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
# GET request example
def get_api_example():
url = "https://api.example.com/data"
headers = {
"Authorization": "Bearer your-token-here"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
print(f"Status Code: {response.status_code}")
print(f"Response: {response.json()}")
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
# Call the functions
if __name__ == "__main__":
post_api_example()
get_api_example()
urllib (built-in library)import urllib.request
import urllib.parse
import json
def post_api_urllib():
url = "https://api.example.com/endpoint"
# Data to send
data = {
"key1": "value1",
"key2": "value2"
}
# Convert data to JSON and encode
json_data = json.dumps(data).encode('utf-8')
# Create request
req = urllib.request.Request(url, data=json_data)
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', 'Bearer your-token-here')
try:
# Make request
with urllib.request.urlopen(req) as response:
response_data = response.read().decode('utf-8')
print(f"Status Code: {response.getcode()}")
print(f"Response: {json.loads(response_data)}")
except urllib.error.URLError as e:
print(f"Error: {e}")
httpx (modern async/sync library)import httpx
import asyncio
# Synchronous version
def sync_api_example():
url = "https://api.example.com/endpoint"
data = {
"key1": "value1",
"key2": "value2"
}
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer your-token-here"
}
try:
with httpx.Client() as client:
response = client.post(url, json=data, headers=headers)
response.raise_for_status()
print(f"Status Code: {response.status_code}")
print(f"Response: {response.json()}")
except httpx.RequestError as e:
print(f"Error: {e}")
# Asynchronous version
async def async_api_example():
url = "https://api.example.com/endpoint"
data = {
"key1": "value1",
"key2": "value2"
}
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer your-token-here"
}
try:
async with httpx.AsyncClient() as client:
response = await client.post(url, json=data, headers=headers)
response.raise_for_status()
print(f"Status Code: {response.status_code}")
print(f"Response: {response.json()}")
except httpx.RequestError as e:
print(f"Error: {e}")
# Run async function
if __name__ == "__main__":
asyncio.run(async_api_example())
import requests
from typing import Dict, Any, Optional
class APIClient:
def __init__(self, base_url: str, token: Optional[str] = None):
self.base_url = base_url.rstrip('/')
self.session = requests.Session()
if token:
self.session.headers.update({
'Authorization': f'Bearer {token}'
})
def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict[Any, Any]:
url = f"{self.base_url}/{endpoint.lstrip('/')}"
try:
response = self.session.request(method, url, **kwargs)
response.raise_for_status()
return {
'status_code': response.status_code,
'data': response.json() if response.content else None,
'headers': dict(response.headers)
}
except requests.exceptions.RequestException as e:
return {
'error': str(e),
'status_code': getattr(e.response, 'status_code', None)
}
def get(self, endpoint: str, params: Optional[Dict] = None) -> Dict[Any, Any]:
return self._make_request('GET', endpoint, params=params)
def post(self, endpoint: str, data: Optional[Dict] = None) -> Dict[Any, Any]:
return self._make_request('POST', endpoint, json=data)
def put(self, endpoint: str, data: Optional[Dict] = None) -> Dict[Any, Any]:
return self._make_request('PUT', endpoint, json=data)
def delete(self, endpoint: str) -> Dict[Any, Any]:
return self._make_request('DELETE', endpoint)
# Usage example
if __name__ == "__main__":
# Initialize client
client = APIClient("https://api.example.com", token="your-token-here")
# POST request
post_data = {"name": "John", "email": "john@example.com"}
result = client.post("/users", post_data)
print("POST Result:", result)
# GET request
result = client.get("/users/1")
print("GET Result:", result)
# GET with parameters
result = client.get("/users", params={"page": 1, "limit": 10})
print("GET with params:", result)
For the requests library:
pip install requests
For the httpx library:
pip install httpx
The urllib library is built into Python, so no installation is needed.
Content-Type for JSON dataChoose the approach that best fits your needs. The requests library is usually the best choice for most use cases due to its simplicity and widespread adoption.