Examples¶
This section contains practical examples of using RequestX for common tasks.
- Basic Usage Examples
- Simple GET Request
- GET with Parameters
- POST with Form Data
- POST with JSON Data
- Custom Headers
- Working with Response Data
- HTTP Methods
- Basic Authentication
- Handling Cookies
- Timeout Configuration
- Error Handling
- File Upload
- Query String Building
- Response Status Checking
- Working with Different Content Types
Overview¶
These examples demonstrate real-world usage patterns for RequestX, from simple GET requests to advanced async patterns and performance optimization techniques.
- Basic Examples
Simple synchronous usage patterns that work exactly like the
requestslibrary.- Async Examples
Asynchronous usage with
async/awaitfor high-performance applications.- Session Examples
Using sessions for connection reuse, authentication, and state management.
- Advanced Examples
Complex scenarios including error handling, retries, streaming, and file uploads.
- Migration Examples
Side-by-side comparisons showing how to migrate from
requeststo RequestX.- Performance Examples
Optimization techniques and benchmarking code.
Quick Examples¶
Simple GET Request
import requestx
response = requestx.get('https://api.github.com/users/octocat')
user_data = response.json()
print(f"User: {user_data['name']}")
POST with JSON
import requestx
data = {'name': 'John Doe', 'email': 'john@example.com'}
response = requestx.post('https://api.example.com/users', json=data)
if response.status_code == 201:
print("User created successfully!")
Async Concurrent Requests
import asyncio
import requestx
async def fetch_multiple():
urls = [
'https://api.github.com/users/octocat',
'https://api.github.com/users/defunkt',
'https://api.github.com/users/pjhyett'
]
tasks = [requestx.get(url) for url in urls]
responses = await asyncio.gather(*tasks)
return [r.json() for r in responses]
users = asyncio.run(fetch_multiple())
Session with Authentication
import requestx
session = requestx.Session()
session.headers.update({'Authorization': 'Bearer your-token'})
# All requests in this session will include the auth header
response = session.get('https://api.example.com/protected')
data = response.json()
Error Handling
import requestx
from requestx import HTTPError, ConnectionError, Timeout
try:
response = requestx.get('https://api.example.com/data', timeout=10)
response.raise_for_status()
return response.json()
except HTTPError as e:
print(f"HTTP error {e.response.status_code}: {e}")
except ConnectionError:
print("Failed to connect to the server")
except Timeout:
print("Request timed out")
Use Case Categories¶
- Web Scraping
Examples for scraping websites efficiently with RequestX’s performance benefits.
- API Integration
Patterns for integrating with REST APIs, handling authentication, and managing rate limits.
- Microservices Communication
Service-to-service communication patterns using async RequestX.
- Data Processing
Fetching and processing large datasets with concurrent requests.
- Testing and Mocking
Examples of testing HTTP clients and mocking responses.
- File Operations
Uploading and downloading files with progress tracking.
Getting Started¶
If you’re new to RequestX:
Start with Basic Usage Examples for fundamental patterns
Move to async-usage for performance-critical applications
Check sessions for advanced connection management
Explore advanced for complex scenarios
If you’re migrating from requests:
Review migration-examples for side-by-side comparisons
Check performance-examples to see the benefits
Use Migration from Requests for a complete migration guide
Code Organization¶
All examples follow these conventions:
Imports: Clear import statements at the top
Error Handling: Proper exception handling where appropriate
Comments: Explanatory comments for complex logic
Type Hints: Type annotations for better code clarity
Best Practices: Following RequestX and Python best practices
Running Examples¶
All examples can be run directly:
# Save example to a file
python example.py
# Or run interactively
python -i example.py
Most examples use public APIs like httpbin.org for demonstration, so they work out of the box without requiring API keys or setup.
Contributing Examples¶
Have a useful RequestX example? We’d love to include it! See our contributing guide for details on submitting examples.
Good examples should:
Solve a real-world problem
Include error handling
Be well-commented
Follow Python best practices
Work with public APIs when possible