The requests module allows you to send HTTP requests using regular Python on the desktop. The adafruit_requests library does the same in CircuitPython.
The HTTP request returns a Response object with all the response data (content, encoding, status, etc).
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
# Updated for Circuit Python 9.0
"""WiFi Simpletest"""
import os
import adafruit_connection_manager
import wifi
import adafruit_requests
# Get WiFi details, ensure these are setup in settings.toml
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_GET_URL = "https://httpbin.org/get"
JSON_POST_URL = "https://httpbin.org/post"
# Initalize Wifi, Socket Pool, Request Session
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
requests = adafruit_requests.Session(pool, ssl_context)
rssi = wifi.radio.ap_info.rssi
print(f"\nConnecting to {ssid}...")
print(f"Signal Strength: {rssi}")
try:
# Connect to the Wi-Fi network
wifi.radio.connect(ssid, password)
except OSError as e:
print(f"❌ OSError: {e}")
print("✅ Wifi!")
print(f" | GET Text Test: {TEXT_URL}")
with requests.get(TEXT_URL) as response:
print(f" | ✅ GET Response: {response.text}")
print("-" * 80)
print(f" | GET Full Response Test: {JSON_GET_URL}")
with requests.get(JSON_GET_URL) as response:
print(f" | ✅ Unparsed Full JSON Response: {response.json()}")
print("-" * 80)
DATA = "This is an example of a JSON value"
print(f" | ✅ JSON 'value' POST Test: {JSON_POST_URL} {DATA}")
with requests.post(JSON_POST_URL, data=DATA) as response:
json_resp = response.json()
# Parse out the 'data' key from json_resp dict.
print(f" | ✅ JSON 'value' Response: {json_resp['data']}")
print("-" * 80)
json_data = {"Date": "January 1, 1970"}
print(f" | ✅ JSON 'key':'value' POST Test: {JSON_POST_URL} {json_data}")
with requests.post(JSON_POST_URL, json=json_data) as response:
json_resp = response.json()
# Parse out the 'json' key from json_resp dict.
print(f" | ✅ JSON 'key':'value' Response: {json_resp['json']}")
print("-" * 80)
print("Finished!")
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
# Updated for Circuit Python 9.0
"""WiFi Advanced Example"""
import os
import adafruit_connection_manager
import wifi
import adafruit_requests
# Get WiFi details, ensure these are setup in settings.toml
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
# Initalize Wifi, Socket Pool, Request Session
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
requests = adafruit_requests.Session(pool, ssl_context)
rssi = wifi.radio.ap_info.rssi
# URL for GET request
JSON_GET_URL = "https://httpbin.org/get"
# Define a custom header as a dict.
headers = {"user-agent": "blinka/1.0.0"}
print(f"\nConnecting to {ssid}...")
print(f"Signal Strength: {rssi}")
try:
# Connect to the Wi-Fi network
wifi.radio.connect(ssid, password)
except OSError as e:
print(f"❌ OSError: {e}")
print("✅ Wifi!")
# Define a custom header as a dict.
headers = {"user-agent": "blinka/1.0.0"}
print(f" | Fetching URL {JSON_GET_URL}")
# Use with statement for retreiving GET request data
with requests.get(JSON_GET_URL, headers=headers) as response:
json_data = response.json()
headers = json_data["headers"]
content_type = response.headers.get("content-type", "")
date = response.headers.get("date", "")
if response.status_code == 200:
print(f" | 🆗 Status Code: {response.status_code}")
else:
print(f" | ❌ Status Code: {response.status_code}")
print(f" | | Custom User-Agent Header: {headers['User-Agent']}")
print(f" | | Content-Type: {content_type}")
print(f" | | Response Timestamp: {date}")
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import os
import adafruit_connection_manager
import board
import busio
from adafruit_esp32spi import adafruit_esp32spi
from digitalio import DigitalInOut
import adafruit_requests
# Get WiFi details, ensure these are setup in settings.toml
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
# If you have an AirLift Featherwing or ItsyBitsy Airlift:
# esp32_cs = DigitalInOut(board.D13)
# esp32_ready = DigitalInOut(board.D11)
# esp32_reset = DigitalInOut(board.D12)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
radio = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
print("Connecting to AP...")
while not radio.is_connected:
try:
radio.connect_AP(ssid, password)
except RuntimeError as e:
print("could not connect to AP, retrying: ", e)
continue
print("Connected to", str(radio.ap_info.ssid, "utf-8"), "\tRSSI:", radio.ap_info.rssi)
# Initialize a requests session
pool = adafruit_connection_manager.get_radio_socketpool(radio)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(radio)
requests = adafruit_requests.Session(pool, ssl_context)
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_GET_URL = "https://httpbin.org/get"
JSON_POST_URL = "https://httpbin.org/post"
print(f"Fetching text from {TEXT_URL}")
with requests.get(TEXT_URL) as response:
print("-" * 40)
print("Text Response: ", response.text)
print("-" * 40)
print(f"Fetching JSON data from {JSON_GET_URL}")
with requests.get(JSON_GET_URL) as response:
print("-" * 40)
print("JSON Response: ", response.json())
print("-" * 40)
data = "31F"
print(f"POSTing data to {JSON_POST_URL}: {data}")
with requests.post(JSON_POST_URL, data=data) as response:
print("-" * 40)
json_resp = response.json()
# Parse out the 'data' key from json_resp dict.
print("Data received from server:", json_resp["data"])
print("-" * 40)
json_data = {"Date": "July 25, 2019"}
print(f"POSTing data to {JSON_POST_URL}: {json_data}")
with requests.post(JSON_POST_URL, json=json_data) as response:
print("-" * 40)
json_resp = response.json()
# Parse out the 'json' key from json_resp dict.
print("JSON Data received from server:", json_resp["json"])
print("-" * 40)
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import adafruit_connection_manager
import board
import busio
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
from digitalio import DigitalInOut
import adafruit_requests
cs = DigitalInOut(board.D10)
spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
# Initialize ethernet interface with DHCP
radio = WIZNET5K(spi_bus, cs)
# Initialize a requests session
pool = adafruit_connection_manager.get_radio_socketpool(radio)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(radio)
requests = adafruit_requests.Session(pool, ssl_context)
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_GET_URL = "http://httpbin.org/get"
JSON_POST_URL = "http://httpbin.org/post"
print(f"Fetching text from {TEXT_URL}")
with requests.get(TEXT_URL) as response:
print("-" * 40)
print("Text Response: ", response.text)
print("-" * 40)
print(f"Fetching JSON data from {JSON_GET_URL}")
with requests.get(JSON_GET_URL) as response:
print("-" * 40)
print("JSON Response: ", response.json())
print("-" * 40)
data = "31F"
print(f"POSTing data to {JSON_POST_URL}: {data}")
with requests.post(JSON_POST_URL, data=data) as response:
print("-" * 40)
json_resp = response.json()
# Parse out the 'data' key from json_resp dict.
print("Data received from server:", json_resp["data"])
print("-" * 40)
json_data = {"Date": "July 25, 2019"}
print(f"POSTing data to {JSON_POST_URL}: {json_data}")
with requests.post(JSON_POST_URL, json=json_data) as response:
print("-" * 40)
json_resp = response.json()
# Parse out the 'json' key from json_resp dict.
print("JSON Data received from server:", json_resp["json"])
print("-" * 40)
Resources
ReadTheDocs
Examples
Page last edited January 22, 2025
Text editor powered by tinymce.