Async Http Patterns logo

Async Http Patterns

Community
manikosto
async-http-patterns

Async HTTP client patterns for Python — httpx, aiohttp, retry strategies, connection pooling, streaming, and testing with respx.

Overview

Publishermanikosto
Repositoryclaude-code-python-stack
Skill nameasync-http-patterns
Stars
54
Forks
10
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by manikosto on GitHub. Read the source before you install it.

Installation

Install the Async Http Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/manikosto/claude-code-python-stack/tree/main/skills/async-http-patterns
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/manikosto/claude-code-python-stack.git /tmp/claude-code-python-stack
mkdir -p .claude/skills
cp -r /tmp/claude-code-python-stack/skills/async-http-patterns .claude/skills/async-http-patterns
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Async Http Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Async Http Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Async Http Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Async HTTP Client Patterns

Patterns for making HTTP requests in async Python applications.

When to Activate

  • Making HTTP requests to external APIs
  • Implementing API clients/wrappers
  • Handling retries and timeouts
  • Streaming large responses
  • Testing HTTP interactions

httpx (Recommended)

Basic Usage

python
import httpx

# Sync
response = httpx.get("https://api.example.com/users")
response.raise_for_status()
data = response.json()

# Async
async with httpx.AsyncClient() as client:
    response = await client.get("https://api.example.com/users")
    response.raise_for_status()
    data = response.json()

Reusable Client with Connection Pooling

python
import httpx
from contextlib import asynccontextmanager

class APIClient:
    def __init__(self, base_url: str, api_key: str):
        self.client = httpx.AsyncClient(
            base_url=base_url,
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=httpx.Timeout(30.0, connect=5.0),
            limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
        )

    async def get_user(self, user_id: int) -> dict:
        response = await self.client.get(f"/users/{user_id}")
        response.raise_for_status()
        return response.json()

    async def create_user(self, data: dict) -> dict:
        response = await self.client.post("/users", json=data)
        response.raise_for_status()
        return response.json()

    async def close(self):
        await self.client.aclose()

Retry with Exponential Backoff

python
import asyncio
import httpx
from typing import TypeVar

T = TypeVar("T")

async def retry_request(
    client: httpx.AsyncClient,
    method: str,
    url: str,
    max_retries: int = 3,
    base_delay: float = 1.0,
    **kwargs,
) -> httpx.Response:
    last_exc = None
    for attempt in range(max_retries + 1):
        try:
            response = await client.request(method, url, **kwargs)
            if response.status_code < 500:
                return response
            # Retry on 5xx
            last_exc = httpx.HTTPStatusError(
                f"Server error: {response.status_code}",
                request=response.request,
                response=response,
            )
        except (httpx.ConnectError, httpx.ReadTimeout) as exc:
            last_exc = exc

        if attempt < max_retries:
            delay = base_delay * (2 ** attempt)
            await asyncio.sleep(delay)

    raise last_exc

Streaming Large Responses

python
async def download_file(url: str, output_path: str):
    async with httpx.AsyncClient() as client:
        async with client.stream("GET", url) as response:
            response.raise_for_status()
            with open(output_path, "wb") as f:
                async for chunk in response.aiter_bytes(chunk_size=8192):
                    f.write(chunk)

Concurrent Requests

python
import asyncio
import httpx

async def fetch_all(urls: list[str]) -> list[dict]:
    async with httpx.AsyncClient() as client:
        tasks = [client.get(url) for url in urls]
        responses = await asyncio.gather(*tasks, return_exceptions=True)

        results = []
        for url, response in zip(urls, responses):
            if isinstance(response, Exception):
                results.append({"url": url, "error": str(response)})
            else:
                results.append({"url": url, "data": response.json()})
        return results

Rate-Limited Client

python
import asyncio

class RateLimitedClient:
    def __init__(self, client: httpx.AsyncClient, requests_per_second: float = 10):
        self.client = client
        self.semaphore = asyncio.Semaphore(int(requests_per_second))
        self.delay = 1.0 / requests_per_second

    async def get(self, url: str, **kwargs) -> httpx.Response:
        async with self.semaphore:
            response = await self.client.get(url, **kwargs)
            await asyncio.sleep(self.delay)
            return response

aiohttp

python
import aiohttp

async def fetch_with_aiohttp(url: str) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            response.raise_for_status()
            return await response.json()

# With connection pooling
connector = aiohttp.TCPConnector(limit=100, limit_per_host=20)
session = aiohttp.ClientSession(connector=connector)

Testing with respx

python
import respx
import httpx
import pytest

@respx.mock
@pytest.mark.asyncio
async def test_get_user():
    respx.get("https://api.example.com/users/1").mock(
        return_value=httpx.Response(200, json={"id": 1, "name": "Alice"})
    )

    async with httpx.AsyncClient() as client:
        response = await client.get("https://api.example.com/users/1")
        assert response.json()["name"] == "Alice"

@respx.mock
@pytest.mark.asyncio
async def test_api_error():
    respx.get("https://api.example.com/users/999").mock(
        return_value=httpx.Response(404, json={"error": "Not found"})
    )

    async with httpx.AsyncClient() as client:
        response = await client.get("https://api.example.com/users/999")
        assert response.status_code == 404

Quick Reference

Featurehttpxaiohttp
Sync + AsyncYesAsync only
HTTP/2YesNo
Connection poolingBuilt-inBuilt-in
Streamingaiter_bytes()content.read()
Testingrespxaioresponses
FastAPI testingAsyncClient + ASGITransportN/A

Frequently asked questions

What does the Async Http Patterns AI skill do?

Async HTTP client patterns for Python — httpx, aiohttp, retry strategies, connection pooling, streaming, and testing with respx.

Why use Async Http Patterns on TypingMind?

Because you install it once and use it with any model. Async Http Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Async Http Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/manikosto/claude-code-python-stack/tree/main/skills/async-http-patterns. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Async Http Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Async Http Patterns?

As many as you like. As long as a model supports skills, you can use Async Http Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Async Http Patterns AI skill free?

It is published on GitHub by manikosto. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇