Adafruit CircuitPython Requests
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.
Common errors
-
ImportError: no module named 'socketpool'
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.fixFor 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. -
NameError: name 'requests' is not defined
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`.fixAfter `import adafruit_requests`, you need to instantiate a session: `requests = adafruit_requests.Session(pool, ssl.create_default_context())` (after setting up `pool` and `ssl`). -
OSError: -2
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.fixVerify 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.
Warnings
- gotcha 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.
- gotcha Microcontrollers have limited memory. Large HTTP responses (e.g., big JSON files, images) can quickly exhaust RAM, leading to `MemoryError` or system crashes.
- gotcha 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.
- gotcha HTTP requests are typically blocking operations. A long request or a network timeout can freeze your CircuitPython program until it completes or fails.
Install
-
pip install adafruit-circuitpython-requests -
circup install adafruit_requests
Imports
- Session
import requests
import adafruit_requests import socketpool import wifi # ... setup wifi and socketpool requests = adafruit_requests.Session(pool, ssl.create_default_context())
Quickstart
import ssl
import socketpool # Required for network communication
import wifi # Required for WiFi connectivity
import adafruit_requests
# --- This section requires CircuitPython board setup ---
# In a real CircuitPython environment, you'd connect to WiFi:
# try:
# from secrets import secrets
# except ImportError:
# print("WiFi secrets are kept in secrets.py, please add them there!")
# raise
# wifi.radio.connect(secrets["ssid"], secrets["password"])
# pool = socketpool.SocketPool(wifi.radio)
# --- For demonstration purposes (not runnable without actual network setup) ---
# Mock objects for local run-ability, replace with real ones on device:
class MockRadio:
ipv4_address = "192.168.1.100"
class MockSocketPool:
def __init__(self, radio):
pass
# In a real scenario, this would create actual sockets
def socket(self, family, type, proto=0):
raise NotImplementedError("Mock socketpool does not provide real sockets")
class MockSSLContext:
def __init__(self):
pass
# Replace these mocks with real objects on a CircuitPython board
wifi.radio = MockRadio()
pool = MockSocketPool(wifi.radio)
ssl_context = MockSSLContext()
# Initialize the requests session with a socket pool and SSL context
# On a real CircuitPython device: requests = adafruit_requests.Session(pool, ssl.create_default_context())
requests = adafruit_requests.Session(pool, ssl_context)
# Make a GET request (this will fail in mock, but demonstrates API)
try:
response = requests.get("http://example.com/api/data")
print(f"Status Code: {response.status_code}")
print(f"Response Text: {response.text}")
response.close()
except Exception as e:
print(f"Error making request (expected in mock setup): {e}")
# Make a POST request with JSON data
post_data = {"key": "value"}
try:
response = requests.post("http://example.com/api/submit", json=post_data)
print(f"POST Status Code: {response.status_code}")
print(f"POST Response Text: {response.text}")
response.close()
except Exception as e:
print(f"Error making POST request (expected in mock setup): {e}")