responses: Mocking Python Requests for Robust Testing

This repository profile is provided by osrepos.com, an open source repository discovery platform.

responses: Mocking Python Requests for Robust Testing

Summary

responses is a Python library designed to simplify the process of mocking the `requests` library during testing. It allows developers to define predictable HTTP responses, enabling isolated and reliable unit tests for applications that interact with external APIs. This utility is essential for ensuring test stability and speed by avoiding actual network calls.

Repository Information

Analyzed by OSRepos on February 17, 2026

Topics

Click on any tag to explore related repositories

Use at your own risk

OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of code from these repositories is the user's own responsibility. Always review the repository, source code, dependencies, licenses, and security implications before running or installing anything. OSRepos is not responsible for issues, damages, or losses resulting from third-party repositories.

Introduction

responses is a powerful utility library for mocking out the Python requests library. It enables developers to simulate HTTP responses in their tests, making it easier to write isolated, fast, and reliable unit tests for applications that depend on external APIs. With responses, you can register mock responses for specific URLs and HTTP methods, define custom status codes, headers, and body content, and even handle dynamic responses using callbacks. It supports various matching criteria for requests, including URL, query parameters, JSON bodies, and headers.

Installation

Installing responses is straightforward using pip:

pip install responses

Examples

Basic Usage

The core of responses involves registering mock responses and activating the mocking functionality, typically with the @responses.activate decorator:

import responses
import requests

@responses.activate
def test_simple_get():
    responses.get(
        "http://twitter.com/api/1/foobar",
        json={"error": "not found"},
        status=404,
    )
    resp = requests.get("http://twitter.com/api/1/foobar")
    assert resp.json() == {"error": "not found"}
    assert resp.status_code == 404

Context Manager

Alternatively, you can use responses as a context manager, which limits its scope to a specific block of code:

import responses
import requests

def test_my_api_context():
    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.GET,
            "http://twitter.com/api/1/foobar",
            body="{}",
            status=200,
            content_type="application/json",
        )
        resp = requests.get("http://twitter.com/api/1/foobar")
        assert resp.status_code == 200

Matching Requests

responses provides powerful matchers to precisely control which mock response is returned based on the incoming request's attributes. This includes matching based on JSON encoded data, URL-encoded parameters, query parameters, request headers, and even custom keyword arguments.

Here's an example using a JSON body matcher:

import responses
import requests
from responses import matchers

@responses.activate
def test_json_matcher():
    responses.post(
        url="http://example.com/",
        body="one",
        match=[
            matchers.json_params_matcher({"page": {"name": "first", "type": "json"}})
        ],
    )
    resp = requests.request(
        "POST",
        "http://example.com/",
        headers={"Content-Type": "application/json"},
        json={"page": {"name": "first", "type": "json"}},
    )
    assert resp.status_code == 200

Dynamic Responses with Callbacks

For more complex scenarios, responses allows you to define dynamic responses using callback functions. These callbacks receive the incoming request and can return a custom status, headers, and body, enabling highly flexible test setups.

import json
import responses
import requests

@responses.activate
def test_dynamic_response():
    def request_callback(request):
        payload = json.loads(request.body)
        resp_body = {"value": sum(payload["numbers"])}
        headers = {"request-id": "123"}
        return (200, headers, json.dumps(resp_body))

    responses.add_callback(
        responses.POST,
        "http://calc.com/sum",
        callback=request_callback,
        content_type="application/json",
    )

    resp = requests.post(
        "http://calc.com/sum",
        json.dumps({"numbers": [1, 2, 3]}),
        headers={"content-type": "application/json"},
    )
    assert resp.json() == {"value": 6}

Why Use It

Using responses brings significant advantages to your Python testing workflow. It ensures that your tests are fast and deterministic, as they don't rely on external network conditions or slow API calls. By isolating your application logic from external dependencies, you can write more robust and reliable tests that accurately reflect your code's behavior. This also makes it easier to test error handling, edge cases, and different API responses without needing to set up complex test servers.

Links

Related repositories

Similar repositories that may be relevant next.

agent-tackle-box: A Terminal Debugger for LangGraph & LangChain Agents

agent-tackle-box: A Terminal Debugger for LangGraph & LangChain Agents

August 15, 2026

agent-tackle-box is a comprehensive toolkit for developing AI agents, featuring the powerful `agent-debugger`. This terminal debugger provides deep insights into LangGraph and LangChain agents. It allows developers to inspect state, monitor tool calls, and step through Python code, all within a unified Textual UI.

agent-debuggerai-agentslangchain
ADR: Uber's Enterprise Security System for AI Agents

ADR: Uber's Enterprise Security System for AI Agents

August 14, 2026

ADR (Agentic AI Detection and Response) is an enterprise security system developed by Uber to secure AI agents. It offers critical capabilities like observability, security benchmarking, and threat detection, ensuring the safe operation of both employee and customer-facing AI applications. This open-source project is deployed in production at Uber and was accepted to MLSys 2026.

PythonAI SecurityAgent Security
SkillOpt: Optimizing Self-Evolving Agent Skills for LLMs

SkillOpt: Optimizing Self-Evolving Agent Skills for LLMs

August 11, 2026

SkillOpt is an innovative text-space optimizer from Microsoft that enables the training of reusable natural-language skills for frozen LLM agents. It approaches skill development with the rigor of deep-learning optimization, using trajectory-driven edits and validation-gated updates. This results in deployable `best_skill.md` artifacts that significantly boost agent performance across various benchmarks and models without modifying model weights.

agent-skillsself-evolving-agentsPython
Ragas: Supercharge Your LLM Application Evaluations

Ragas: Supercharge Your LLM Application Evaluations

August 9, 2026

Ragas is an ultimate toolkit for evaluating and optimizing Large Language Model (LLM) applications. It offers objective metrics, intelligent test generation, and data-driven insights to move beyond subjective assessments. This framework helps developers build feedback loops and continuously improve their LLM applications.

evaluationllmllmops

Source repository

Open the original repository on GitHub.

11 counted GitHub visits

View on GitHub
OS
OSRepos

Analysis and discovery of open source repositories. Find interesting projects and follow their updates.

Monitor your website with YourWebsiteScore

OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of third-party repository code is at your own risk. Always review source code, dependencies, licenses, and security implications before running anything.

© 2025 OSRepos. Built with Nuxt 3 and lots of ❤️