🛠 Client HTTP : requête GET vers une API

Raspberry Pi Pico 2 W · intermediaire · Schéma : IMG-pico-2-w-intermediaire-5-pico2w-http-client-get.svg — Pico 2 W envoyant une requête HTTP GET vers un serveur distant via la box Internet, réponse JSON affichée en console.

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials