httpx
A next-generation HTTP client for Python with both sync and async support, perfect for modern Python applications
Best use case
httpx is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. A next-generation HTTP client for Python with both sync and async support, perfect for modern Python applications
A next-generation HTTP client for Python with both sync and async support, perfect for modern Python applications
Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.
Practical example
Example input
Use the "httpx" skill to help with this workflow task. Context: A next-generation HTTP client for Python with both sync and async support, perfect for modern Python applications
Example output
A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.
When to use this skill
- Use this skill when you want a reusable workflow rather than writing the same prompt again and again.
When not to use this skill
- Do not use this when you only need a one-off answer and do not need a reusable workflow.
- Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/httpx/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How httpx Compares
| Feature / Agent | httpx | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
A next-generation HTTP client for Python with both sync and async support, perfect for modern Python applications
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# HTTPX Skill
HTTPX is a fully featured HTTP client for Python that provides both synchronous and asynchronous APIs, with support for HTTP/1.1 and HTTP/2.
## Quick Start
### Basic Usage
```python
import httpx
# Simple GET request
response = httpx.get('https://api.example.com/data')
print(response.status_code)
print(response.json())
# POST request with JSON data
response = httpx.post('https://api.example.com/users', json={'name': 'Alice'})
```
### Async Usage
```python
import asyncio
import httpx
async def fetch_data():
async with httpx.AsyncClient() as client:
response = await client.get('https://api.example.com/data')
return response.json()
result = asyncio.run(fetch_data())
```
## Common Patterns
### 1. Async Client with Connection Pooling
```python
import httpx
async def make_multiple_requests():
async with httpx.AsyncClient() as client:
# Reuse the same client for multiple requests
tasks = [
client.get('https://api.example.com/users/1'),
client.get('https://api.example.com/users/2'),
client.get('https://api.example.com/users/3')
]
responses = await asyncio.gather(*tasks)
return [r.json() for r in responses]
```
### 2. Authentication
```python
import httpx
# Basic Authentication
auth = httpx.BasicAuth(username='user', password='pass')
client = httpx.Client(auth=auth)
# Bearer Token Authentication
headers = {'Authorization': 'Bearer your-token-here'}
client = httpx.Client(headers=headers)
# Per-request authentication
response = client.get('https://api.example.com', auth=('user', 'pass'))
```
### 3. Streaming Downloads
```python
import httpx
# Stream large files without loading into memory
with httpx.stream('GET', 'https://example.com/large-file.zip') as response:
with open('large-file.zip', 'wb') as f:
for chunk in response.iter_bytes():
f.write(chunk)
# Async streaming
async def download_large_file():
async with httpx.AsyncClient() as client:
async with client.stream('GET', 'https://example.com/large-file.zip') as response:
with open('large-file.zip', 'wb') as f:
async for chunk in response.aiter_bytes():
f.write(chunk)
```
### 4. Streaming Uploads
```python
import httpx
# Upload large files with streaming
async def upload_large_file():
def generate_data():
# Yield chunks of data
for i in range(100):
yield f'chunk {i}\n'.encode()
async with httpx.AsyncClient() as client:
response = await client.post(
'https://api.example.com/upload',
content=generate_data()
)
return response
```
### 5. Error Handling and Timeouts
```python
import httpx
# Configure timeouts
client = httpx.Client(
timeout=httpx.Timeout(10.0, connect=5.0, read=8.0)
)
try:
response = client.get('https://api.example.com/slow')
response.raise_for_status() # Raise exception for 4XX/5XX responses
except httpx.TimeoutException:
print("Request timed out")
except httpx.HTTPStatusError as e:
print(f"HTTP error: {e.response.status_code}")
except httpx.RequestError as e:
print(f"Request failed: {e}")
```
### 6. Client Configuration
```python
import httpx
# Client with shared configuration
client = httpx.Client(
base_url='https://api.example.com',
headers={'User-Agent': 'MyApp/1.0'},
timeout=30.0,
follow_redirects=True
)
# All requests will use base_url and headers
response = client.get('/users') # Makes request to https://api.example.com/users
```
### 7. Custom Authentication
```python
import httpx
class CustomAuth(httpx.Auth):
def __init__(self, api_key):
self.api_key = api_key
def auth_flow(self, request):
request.headers['X-API-Key'] = self.api_key
yield request
# Use custom auth
auth = CustomAuth('your-secret-api-key')
client = httpx.Client(auth=auth)
```
### 8. Progress Monitoring
```python
import httpx
from tqdm import tqdm
def download_with_progress(url, filename):
with httpx.stream('GET', url) as response:
total = int(response.headers.get('content-length', 0))
with tqdm(total=total, unit='B', unit_scale=True) as progress:
with open(filename, 'wb') as f:
for chunk in response.iter_bytes():
f.write(chunk)
progress.update(len(chunk))
```
### 9. Retry Logic
```python
import httpx
import time
def make_request_with_retry(url, max_retries=3):
for attempt in range(max_retries):
try:
response = httpx.get(url, timeout=10.0)
response.raise_for_status()
return response
except httpx.RequestError as e:
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt) # Exponential backoff
```
### 10. WebSocket Support (with httpx-ws)
```python
import httpx
from httpx_ws import connect_ws
async def websocket_example():
async with httpx.AsyncClient() as client:
async with connect_ws('wss://echo.websocket.org', client) as websocket:
await websocket.send_text('Hello, WebSocket!')
message = await websocket.receive_text()
print(f"Received: {message}")
```
## Practical Code Snippets
### API Client Class
```python
import httpx
from typing import Optional, Dict, Any
class APIClient:
def __init__(self, base_url: str, api_key: str):
self.base_url = base_url
self.client = httpx.Client(
base_url=base_url,
headers={'Authorization': f'Bearer {api_key}'},
timeout=30.0
)
def get(self, endpoint: str, params: Optional[Dict] = None) -> Dict[Any, Any]:
response = self.client.get(endpoint, params=params)
response.raise_for_status()
return response.json()
def post(self, endpoint: str, data: Dict[Any, Any]) -> Dict[Any, Any]:
response = self.client.post(endpoint, json=data)
response.raise_for_status()
return response.json()
def close(self):
self.client.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
# Usage
with APIClient('https://api.example.com', 'your-api-key') as client:
users = client.get('/users')
new_user = client.post('/users', {'name': 'John', 'email': 'john@example.com'})
```
### Async API Client
```python
import httpx
from typing import Optional, Dict, Any
class AsyncAPIClient:
def __init__(self, base_url: str, api_key: str):
self.base_url = base_url
self.client = httpx.AsyncClient(
base_url=base_url,
headers={'Authorization': f'Bearer {api_key}'},
timeout=30.0
)
async def get(self, endpoint: str, params: Optional[Dict] = None) -> Dict[Any, Any]:
response = await self.client.get(endpoint, params=params)
response.raise_for_status()
return response.json()
async def close(self):
await self.client.aclose()
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
# Usage
async def main():
async with AsyncAPIClient('https://api.example.com', 'your-api-key') as client:
users = await client.get('/users')
print(users)
```
## Requirements
```txt
httpx>=0.24.0
# Optional dependencies for additional features:
# httpx-ws>=0.6.0 # WebSocket support
# tqdm>=4.65.0 # Progress bars
# anyio>=3.7.0 # Alternative async runtime
# trio>=0.22.0 # Alternative async runtime
```
## Key Features
- **Sync and Async APIs**: Same interface for both synchronous and asynchronous code
- **HTTP/2 Support**: Full HTTP/2 support with multiplexing
- **Connection Pooling**: Efficient connection management
- **Streaming**: Stream requests and responses without loading everything into memory
- **Authentication**: Built-in support for Basic, Digest, Bearer token, and custom auth
- **Timeouts**: Configurable timeouts for connect, read, and overall requests
- **Redirect Handling**: Configurable redirect following
- **Cookie Handling**: Automatic cookie management
- **Proxy Support**: HTTP and HTTPS proxy support
- **SSL/TLS**: Full SSL/TLS configuration options
## Installation
```bash
uv add httpx
# For HTTP/2 support
uv add httpx[http2]
# For WebSocket support
uv add httpx-ws
```
This skill provides comprehensive HTTP client capabilities for modern Python applications, with excellent async support and production-ready features.Related Skills
azure-quotas
Check/manage Azure quotas and usage across providers. For deployment planning, capacity validation, region selection. WHEN: "check quotas", "service limits", "current usage", "request quota increase", "quota exceeded", "validate capacity", "regional availability", "provisioning limits", "vCPU limit", "how many vCPUs available in my subscription".
raindrop-io
Manage Raindrop.io bookmarks with AI assistance. Save and organize bookmarks, search your collection, manage reading lists, and organize research materials. Use when working with bookmarks, web research, reading lists, or when user mentions Raindrop.io.
zlibrary-to-notebooklm
自动从 Z-Library 下载书籍并上传到 Google NotebookLM。支持 PDF/EPUB 格式,自动转换,一键创建知识库。
discover-skills
当你发现当前可用的技能都不够合适(或用户明确要求你寻找技能)时使用。本技能会基于任务目标和约束,给出一份精简的候选技能清单,帮助你选出最适配当前任务的技能。
web-performance-seo
Fix PageSpeed Insights/Lighthouse accessibility "!" errors caused by contrast audit failures (CSS filters, OKLCH/OKLAB, low opacity, gradient text, image backgrounds). Use for accessibility-driven SEO/performance debugging and remediation.
project-to-obsidian
将代码项目转换为 Obsidian 知识库。当用户提到 obsidian、项目文档、知识库、分析项目、转换项目 时激活。 【激活后必须执行】: 1. 先完整阅读本 SKILL.md 文件 2. 理解 AI 写入规则(默认到 00_Inbox/AI/、追加式、统一 Schema) 3. 执行 STEP 0: 使用 AskUserQuestion 询问用户确认 4. 用户确认后才开始 STEP 1 项目扫描 5. 严格按 STEP 0 → 1 → 2 → 3 → 4 顺序执行 【禁止行为】: - 禁止不读 SKILL.md 就开始分析项目 - 禁止跳过 STEP 0 用户确认 - 禁止直接在 30_Resources 创建(先到 00_Inbox/AI/) - 禁止自作主张决定输出位置
obsidian-helper
Obsidian 智能笔记助手。当用户提到 obsidian、日记、笔记、知识库、capture、review 时激活。 【激活后必须执行】: 1. 先完整阅读本 SKILL.md 文件 2. 理解 AI 写入三条硬规矩(00_Inbox/AI/、追加式、白名单字段) 3. 按 STEP 0 → STEP 1 → ... 顺序执行 4. 不要跳过任何步骤,不要自作主张 【禁止行为】: - 禁止不读 SKILL.md 就开始工作 - 禁止跳过用户确认步骤 - 禁止在非 00_Inbox/AI/ 位置创建新笔记(除非用户明确指定)
internationalizing-websites
Adds multi-language support to Next.js websites with proper SEO configuration including hreflang tags, localized sitemaps, and language-specific content. Use when adding new languages, setting up i18n, optimizing for international SEO, or when user mentions localization, translation, multi-language, or specific languages like Japanese, Korean, Chinese.
google-official-seo-guide
Official Google SEO guide covering search optimization, best practices, Search Console, crawling, indexing, and improving website search visibility based on official Google documentation
github-release-assistant
Generate bilingual GitHub release documentation (README.md + README.zh.md) from repo metadata and user input, and guide release prep with git add/commit/push. Use when the user asks to write or polish README files, create bilingual docs, prepare a GitHub release, or mentions release assistant/README generation.
doc-sync-tool
自动同步项目中的 Agents.md、claude.md 和 gemini.md 文件,保持内容一致性。支持自动监听和手动触发。
deploying-to-production
Automate creating a GitHub repository and deploying a web project to Vercel. Use when the user asks to deploy a website/app to production, publish a project, or set up GitHub + Vercel deployment.