Typing Stubs for requests
types-requests provides static type annotations for the popular `requests` HTTP library. It allows type checkers like Mypy and Pyright to analyze code using `requests` for type correctness. This package, part of the larger Typeshed project, aims to provide accurate annotations for `requests~=2.33.0` and is frequently updated, often daily, from the Typeshed repository.
Warnings
- breaking Version incompatibility with `urllib3` prior to types-requests 2.31.0.7. Versions of `types-requests` from `2.31.0.7` onwards require `urllib3>=2`. If your `requests` installation depends on an older `urllib3<2`, installing a newer `types-requests` will cause type checking issues due to conflicting stub dependencies.
- gotcha Installing `types-requests` does not install `requests` itself. This package only provides type annotations for the `requests` library. The `requests` library must be installed separately for your code to run at runtime.
- gotcha Stub package versioning does not always directly mirror the runtime package version. While the first three parts of `types-requests`'s version generally align with `requests` (e.g., `types-requests==2.33.0.YYYYMMDD` is for `requests~=2.33.0`), the final part is a daily release date from the Typeshed repository. Minor stub updates can introduce new type-checking errors even if the runtime `requests` package has not changed.
- gotcha Do not attempt to import `types_requests` directly in your Python code. Stub packages are automatically discovered by type checkers and are not meant for direct runtime import. Attempting to import it will result in a `ModuleNotFoundError` during program execution.
Install
-
pip install types-requests -
pip install requests types-requests
Imports
- requests
import requests
- requests.Session
import requests session: requests.Session = requests.Session()
Quickstart
import requests
from typing import Dict, Any
def fetch_data(url: str, params: Dict[str, str] = {}) -> Dict[str, Any]:
"""Fetches JSON data from a URL with type hints provided by types-requests."""
try:
response = requests.get(url, params=params)
response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as e:
print(f"HTTP error occurred: {e}")
raise
except requests.exceptions.RequestException as e:
print(f"An error occurred during the request: {e}")
raise
# Example usage:
if __name__ == "__main__":
base_url = "https://httpbin.org/get"
query_params = {"key1": "value1", "key2": "value2"}
try:
data = fetch_data(base_url, query_params)
print("Fetched data:")
print(data)
except Exception:
print("Failed to fetch data.")