🛠 Client HTTP : requête GET vers une API
Objectives
Once connected to Wi-Fi (connection tutorial), query an HTTP API: manually build a GET request, read the response, verify the status code, and extract the data. The CYW43439 is limited to 2.4 GHz and its throughput is constrained by the ~33 MHz SPI link to the RP2350: keep responses lightweight.
Hardware
- Pico 2 W connected to Wi-Fi (see pico2w-connexion-wifi)
- MicroPython >= v1.25.0 (or pico-sdk with lwIP)
- A plain HTTP API for testing (example: httpbin.org)
Complete code
# main.py - MicroPython : GET HTTP sur le port 80
import network, socket, time
wlan = network.WLAN
wlan.active(True)
if not wlan.isconnected:
wlan.connect('mon_ssid', 'mon_mot_de_passe')
while not wlan.isconnected:
time.sleep_ms(200)
hote = 'httpbin.org'
chemin = '/get'
s = socket.socket
s.connect(socket.getaddrinfo(hote, 80)[0][-1])
s.send(('GET %s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\n\r\n'
% (chemin, hote)).encode)
entete = s.readline # b'HTTP/1.1 200 OK'
print('Statut :', entete.decode.split[1])
while s.readline.strip: # sauter les entetes
pass
print('Corps :', s.read(120).decode)
s.close
In C, the official pico-examples pico_w/wifi/http_client (picow_http_client.c) does the same thing using tcp_new/tcp_write.
Expected verification
The console displays Status: 200 followed by the first bytes of the JSON body. When Wi-Fi is disconnected, the connection fails gracefully with an exception or an error code instead of blocking the board.
Common errors
- Forgetting the Host: header: many servers return 400.
- Reading the body without consuming the header lines: the JSON appears corrupted.
- Using https:// with a simple socket: TLS is required (see pico2w-wifi-tls-certificats).
- In C, forgetting the cyw43_arch_lwip_begin/end lock around tcp_* calls outside callbacks.
Other tutorials for this board
Code examples for this board
clignotante.pyPythonbouton-interruption.pyPythonpwm-servo.pyPythonlecture-adc.pyPythonneopixel.pyPythonoled-i2c.pyPython