{"id":9433,"library":"adafruit-circuitpython-requests","title":"Adafruit CircuitPython Requests","description":"Adafruit CircuitPython Requests provides a requests-like API for making HTTP requests from CircuitPython microcontrollers. It offers a familiar interface for GET, POST, PUT, DELETE, and HEAD operations, allowing microcontrollers with network capabilities (like WiFi or Ethernet) to interact with web services. The current version is 4.1.16, and it typically follows a rapid release cadence with bug fixes and minor improvements.","status":"active","version":"4.1.16","language":"en","source_language":"en","source_url":"https://github.com/adafruit/Adafruit_CircuitPython_Requests","tags":["CircuitPython","networking","HTTP","requests-like","microcontroller","IoT"],"install":[{"cmd":"pip install adafruit-circuitpython-requests","lang":"bash","label":"For host computer (e.g., Raspberry Pi with Blinka)"},{"cmd":"circup install adafruit_requests","lang":"bash","label":"For CircuitPython device (via circup)"}],"dependencies":[{"reason":"Enables running some CircuitPython libraries on single-board computers like Raspberry Pi with CPython.","package":"adafruit-blinka","optional":true},{"reason":"Provides low-level bus communication utilities, often used by network hardware drivers.","package":"adafruit-circuitpython-busdevice","optional":false},{"reason":"Provides type hinting support for CircuitPython specific types.","package":"adafruit-circuitpython-typing","optional":false}],"imports":[{"note":"The standard 'requests' library is not 'adafruit_requests'. Must use adafruit_requests for CircuitPython.","wrong":"import requests","symbol":"Session","correct":"import adafruit_requests\nimport socketpool\nimport wifi\n# ... setup wifi and socketpool\nrequests = adafruit_requests.Session(pool, ssl.create_default_context())"}],"quickstart":{"code":"import ssl\nimport socketpool # Required for network communication\nimport wifi # Required for WiFi connectivity\nimport adafruit_requests\n\n# --- This section requires CircuitPython board setup ---\n# In a real CircuitPython environment, you'd connect to WiFi:\n# try:\n#     from secrets import secrets\n# except ImportError:\n#     print(\"WiFi secrets are kept in secrets.py, please add them there!\")\n#     raise\n# wifi.radio.connect(secrets[\"ssid\"], secrets[\"password\"])\n# pool = socketpool.SocketPool(wifi.radio)\n\n# --- For demonstration purposes (not runnable without actual network setup) ---\n# Mock objects for local run-ability, replace with real ones on device:\nclass MockRadio:\n    ipv4_address = \"192.168.1.100\"\nclass MockSocketPool:\n    def __init__(self, radio):\n        pass\n    # In a real scenario, this would create actual sockets\n    def socket(self, family, type, proto=0):\n        raise NotImplementedError(\"Mock socketpool does not provide real sockets\")\nclass MockSSLContext:\n    def __init__(self):\n        pass\n# Replace these mocks with real objects on a CircuitPython board\nwifi.radio = MockRadio()\npool = MockSocketPool(wifi.radio)\nssl_context = MockSSLContext()\n\n# Initialize the requests session with a socket pool and SSL context\n# On a real CircuitPython device: requests = adafruit_requests.Session(pool, ssl.create_default_context())\nrequests = adafruit_requests.Session(pool, ssl_context)\n\n# Make a GET request (this will fail in mock, but demonstrates API)\ntry:\n    response = requests.get(\"http://example.com/api/data\")\n    print(f\"Status Code: {response.status_code}\")\n    print(f\"Response Text: {response.text}\")\n    response.close()\nexcept Exception as e:\n    print(f\"Error making request (expected in mock setup): {e}\")\n\n# Make a POST request with JSON data\npost_data = {\"key\": \"value\"}\ntry:\n    response = requests.post(\"http://example.com/api/submit\", json=post_data)\n    print(f\"POST Status Code: {response.status_code}\")\n    print(f\"POST Response Text: {response.text}\")\n    response.close()\nexcept Exception as e:\n    print(f\"Error making POST request (expected in mock setup): {e}\")","lang":"python","description":"This quickstart demonstrates the `adafruit_requests.Session` API. Note that actual network operations on CircuitPython require configuring `wifi.radio` (or Ethernet) and creating a `socketpool.SocketPool` instance, which involves specific hardware and `secrets.py` setup not fully runnable in a generic Python environment. The provided code includes mock objects to illustrate the API without requiring actual hardware, but real network requests will fail."},"warnings":[{"fix":"Ensure you are targeting a CircuitPython board with proper network hardware (WiFi, Ethernet) and an initialized `socketpool`.","message":"This library is designed for CircuitPython microcontrollers. Running it on a standard CPython environment (e.g., PC) will require `adafruit-blinka` and potentially custom `socketpool` and `wifi` implementations or mocks, and won't interact with physical network hardware directly.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Request only necessary data, use streaming where possible, or parse responses chunk by chunk if the API allows. Consider the `response.iter_content()` method for streaming large responses.","message":"Microcontrollers have limited memory. Large HTTP responses (e.g., big JSON files, images) can quickly exhaust RAM, leading to `MemoryError` or system crashes.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always use `ssl.create_default_context()` where possible for HTTPS. For custom certificates or older hardware, consult Adafruit's CircuitPython documentation for specific SSL setup instructions for your board.","message":"SSL/TLS support on microcontrollers is resource-intensive. `ssl.create_default_context()` might not always be available or performant, and specific certificate handling might be required, especially for HTTPS.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Design your application to handle blocking operations gracefully. Consider using asynchronous patterns if available (e.g., `asyncio` on some boards, though not directly supported by `adafruit_requests`), or implement timeouts for requests to prevent indefinite blocking.","message":"HTTP requests are typically blocking operations. A long request or a network timeout can freeze your CircuitPython program until it completes or fails.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"For CircuitPython, ensure your board has a network co-processor and `socketpool` is available. For CPython (e.g., Raspberry Pi), ensure `adafruit-blinka` is installed and properly configured, and provide a compatible socketpool implementation.","cause":"The `socketpool` module is a core CircuitPython networking module and is not part of standard Python. This error typically occurs when running `adafruit_requests` on a standard CPython environment without `adafruit-blinka` or on a CircuitPython board without a network co-processor.","error":"ImportError: no module named 'socketpool'"},{"fix":"After `import adafruit_requests`, you need to instantiate a session: `requests = adafruit_requests.Session(pool, ssl.create_default_context())` (after setting up `pool` and `ssl`).","cause":"You likely imported `adafruit_requests` but did not assign its `Session` object to a variable named `requests` (or any other variable). The `requests` object in `adafruit_requests` is typically an instance of `adafruit_requests.Session`.","error":"NameError: name 'requests' is not defined"},{"fix":"Verify your `secrets.py` for correct WiFi credentials. Check if your board is connected to the WiFi (`wifi.radio.connected`). Ensure the target URL is correct and the server is online. Try pinging the target from another device on the same network.","cause":"This generic `OSError` (often corresponding to `EHOSTUNREACH` or `ENOTCONN`) indicates a fundamental network connectivity issue, such as no WiFi connection, incorrect SSID/password, DNS resolution failure, or target server being unreachable.","error":"OSError: -2"}]}