requests

The requests library provides functions for making HTTP requests, matching Python’s requests library API. Reach for it any time a script needs to call an HTTP/HTTPS API.

Available Functions

Function Description
get(url, **kwargs) Make a GET request.
post(url, data=None, **kwargs) Make a POST request.
put(url, data=None, **kwargs) Make a PUT request.
delete(url, **kwargs) Make a DELETE request.
patch(url, data=None, **kwargs) Make a PATCH request.
parallel(requests, max_parallel=4) Execute multiple HTTP requests concurrently.

Functions

get(url, **kwargs)

Send an HTTP GET request to the specified URL.

Parameters:

  • url (str): URL to request.
  • **kwargs (optional):
    • timeout (int): Request timeout in seconds. Default: 5.
    • headers (dict): HTTP headers to send.
    • params (dict): Query parameters to append to the URL.
    • auth (tuple/list): Basic authentication as (username, password).
    • verify (bool or str): Verify the server’s TLS certificate. Default: True (None too). False accepts any certificate, for a development server only; a path names a PEM bundle file of CA certificates to trust instead of the system’s.

Returns: Response: see Response Object.

import requests

response = requests.get("https://api.example.com/users/1", timeout=10, headers={"Authorization": "Bearer token123"})
if response.status_code == 200:
    print("User data:", response.text)

post(url, data=None, **kwargs)

Send an HTTP POST request to the specified URL with the given data.

Parameters:

  • url (str): URL to request.
  • data (str or bytes, optional): Request body. Use bytes for binary payloads (msgpack, etc.). Default: None.
  • **kwargs (optional):
    • timeout (int): Request timeout in seconds. Default: 5.
    • headers (dict): HTTP headers to send.
    • params (dict): Query parameters to append to the URL.
    • json (dict/list): Data to JSON-encode as the request body (sets Content-Type). Use either data or json, not both.
    • auth (tuple/list): Basic authentication as (username, password).
    • verify (bool or str): Verify the server’s TLS certificate. Default: True (None too). False accepts any certificate, for a development server only; a path names a PEM bundle file of CA certificates to trust instead of the system’s.

Returns: Response: see Response Object.

import json
import requests

new_user = {"name": "Alice", "email": "[email protected]"}
response = requests.post("https://api.example.com/users", json=new_user)

if response.status_code == 201:
    created = response.json()
    print("Created user:", created["id"])

put(url, data=None, **kwargs)

Send an HTTP PUT request to the specified URL with the given data.

Parameters:

  • url (str): URL to request.
  • data (str or bytes, optional): Request body. Use bytes for binary payloads (msgpack, etc.). Default: None.
  • **kwargs (optional):
    • timeout (int): Request timeout in seconds. Default: 5.
    • headers (dict): HTTP headers to send.
    • params (dict): Query parameters to append to the URL.
    • json (dict/list): Data to JSON-encode as the request body (sets Content-Type). Use either data or json, not both.
    • auth (tuple/list): Basic authentication as (username, password).
    • verify (bool or str): Verify the server’s TLS certificate. Default: True (None too). False accepts any certificate, for a development server only; a path names a PEM bundle file of CA certificates to trust instead of the system’s.

Returns: Response: see Response Object.

import requests

response = requests.put("https://api.example.com/users/1", json={"name": "Alice Updated"})

delete(url, **kwargs)

Send an HTTP DELETE request to the specified URL.

Parameters:

  • url (str): URL to request.
  • **kwargs (optional):
    • timeout (int): Request timeout in seconds. Default: 5.
    • headers (dict): HTTP headers to send.
    • params (dict): Query parameters to append to the URL.
    • auth (tuple/list): Basic authentication as (username, password).
    • verify (bool or str): Verify the server’s TLS certificate. Default: True (None too). False accepts any certificate, for a development server only; a path names a PEM bundle file of CA certificates to trust instead of the system’s.

Returns: Response: see Response Object.

import requests

response = requests.delete("https://api.example.com/users/1")

patch(url, data=None, **kwargs)

Send an HTTP PATCH request to the specified URL with the given data.

Parameters:

  • url (str): URL to request.
  • data (str or bytes, optional): Request body. Use bytes for binary payloads (msgpack, etc.). Default: None.
  • **kwargs (optional):
    • timeout (int): Request timeout in seconds. Default: 5.
    • headers (dict): HTTP headers to send.
    • params (dict): Query parameters to append to the URL.
    • json (dict/list): Data to JSON-encode as the request body (sets Content-Type). Use either data or json, not both.
    • auth (tuple/list): Basic authentication as (username, password).
    • verify (bool or str): Verify the server’s TLS certificate. Default: True (None too). False accepts any certificate, for a development server only; a path names a PEM bundle file of CA certificates to trust instead of the system’s.

Returns: Response: see Response Object.

import requests

response = requests.patch("https://api.example.com/users/1", json={"name": "Alice P."})

parallel(requests, max_parallel=4)

Execute multiple HTTP requests concurrently with a configurable concurrency limit. Results are returned in the same order as the input requests, regardless of completion order.

Parameters:

  • requests (list): List of request specification dicts, each containing:
    • method (str): HTTP method: "GET", "POST", "PUT", "DELETE", or "PATCH". Default: "GET".
    • url (str): The URL to request. Required.
    • data (str or bytes, optional): Request body (string or binary).
    • json (dict/list, optional): Data to JSON-encode as the request body (sets Content-Type).
    • headers (dict, optional): HTTP headers.
    • params (dict, optional): Query parameters to append to the URL.
    • auth (list/tuple, optional): Basic authentication as [username, password].
    • timeout (int, optional): Request timeout in seconds. Default: 30.
    • verify (bool or str, optional): Verify the server’s TLS certificate. Default: True. A path names a CA bundle; one outside --allowed-paths raises PermissionError for the whole batch.
  • max_parallel (int, optional): Maximum number of concurrent requests. Default: 4. The host may cap this (see Script Resource Limits); a larger request is reduced to the cap.

Returns: list: Response objects in the same order as the input list. A request that fails for any reason, a malformed spec (missing url or un-encodable json), a transport failure (timeout, DNS, connection refused) or a response over the interpreter’s limits, yields a Response with status_code=0 and the error message in text in the corresponding position, so one failure never stops the batch.

import requests

results = requests.parallel([
    {"method": "GET", "url": "https://api.example.com/items/1"},
    {"method": "GET", "url": "https://api.example.com/items/2"},
    {"method": "POST", "url": "https://api.example.com/items", "json": {"name": "new"}},
], max_parallel=4)

for resp in results:
    if resp.status_code == 200:
        data = resp.json()
        print(data)

Response Object

All HTTP functions return a Response object with the following attributes, accessible either as properties or by indexing:

  • status_code / ["status_code"] (int): HTTP status code.
  • text / ["text"] (str): Response body decoded as a string.
  • content / ["content"] (bytes): Raw response body. Use this instead of .text for binary content (images, msgpack, etc.).
  • body / ["body"] (str): Deprecated alias for text.
  • headers / ["headers"] (dict): Response headers.
  • url / ["url"] (str): The URL of the response.

Response.json()

Parse the response body as JSON.

Returns: dict/list: the parsed JSON body.

data = response.json()

Response.raise_for_status()

Raise an exception if the status code indicates an error (>= 400).

Returns: None

Raises: HTTPError: if the status code is >= 400.

import requests

try:
    response = requests.get("https://api.example.com/data")
    response.raise_for_status()
except requests.HTTPError as e:
    print("HTTP error:", e)
except requests.RequestException as e:
    print("Request failed:", e)

Exceptions

The requests library exposes the following exception types for error handling:

  • RequestException: base exception for all request errors.
  • HTTPError: raised by raise_for_status() for HTTP error responses (4xx, 5xx).

Security Considerations

This is an extended library, requiring registration in Go, see Library Registration.

requests uses an unrestricted pooled HTTP client when the embedder calls RegisterRequestsLibrary without a policy. Embedders can instead pass a non-nil *netsecurity.Config; this enables the built-in guard, including host allow/deny rules, address-category and CIDR controls, HTTPS/IP-literal settings, redirect checks, and DNS-rebinding-resistant validated-IP dialing. A non-nil zero-value config applies safe defaults, and an invalid config fails closed.

The CLI configures the same guard through its --network-policy TOML file and passes that policy to requests; scripts do not configure it through request arguments. This policy is specific to participating clients, not a blanket process firewall, so do not assume raw networking, messaging, container, Nomad, plugin, or provisioning clients inherit it. See the Security Guide.

verify changes only which certificates are trusted (False: any); under a network policy every other rule still applies. A CA bundle path is read like any file: under --allowed-paths it must lie within them, else an uncatchable PermissionError.

Notes

  • HTTP/2 support with automatic fallback to HTTP/1.1.
  • Connection pooling (100 connections per host).
  • Self-signed certificates are rejected by default. To trust one, pass verify="ca.pem", a PEM bundle of the CA certificates to trust instead of the system’s (as in Python’s requests, it replaces them: include the system’s own to reach other sites too); verify=False accepts any certificate, for a development server only.
  • Default timeout: 5 seconds (30 seconds for parallel()).

See Also