Raspberry Pi Pico W: Getting Started with HTTP GET Requests (MicroPython)

This tutorial is a getting started guide to HTTP GET requests with the Raspberry Pi Pico W. HTTP Requests are fundamental to interact with web services to retrieve data from external sources, integrate with web APIs to access third-party services, and much more.

In this guide, you’ll learn the basic concepts of HTTP GET requests and test some simple examples to get data from the internet.

Raspberry Pi Pico W Getting Started with HTTP GET Requests MicroPython

When it comes to IoT projects, HTTP requests are fundamental to interact with web services to retrieve data from external sources, integrate with Web APIs to access web services, or even remote control your Pico using external third-party platforms.

New to the Raspberry Pi Pico? Read the following guide: Getting Started with Raspberry Pi Pico (and Pico W).

Table of Contents

Throughout this tutorial, we’ll cover the following topics.

Prerequisites

Before proceeding, make sure you check the following prerequisites:

MicroPython Firmware

To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board.

micorpython logo

The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.

Alternatively, if you like programming using VS Code, you can start with the following tutorial:

What are HTTP Requests?

The most common way to exchange data with another computer (server) on the internet is using the HTTP protocol.

HTTP (Hypertext Transfer Protocol) works through a client-server model. In this model, the client communicates with a server using HTTP requests. An HTTP request is a message sent by the client to a server, typically to request a specific action or retrieve information. The server sends a response back to the client also through HTTP.

Raspberry Pi Pico HTTP GET Request
  • Client: initiates communication through a request.
  • Server: receives and processes the request and sends a response in return.

The Raspberry Pi Pico can either be a client or a server. When it is a client, it sends requests to servers. When it is a server, it handles the client’s requests.

Related content: Raspberry Pi Pico: Web Server (MicroPython)

In this tutorial, we’ll take a look at the Raspberry Pi Pico as an HTTP client.

Here are some examples of what you can do using HTTP requests with the Pico:

  • Get data from the internet: for example, time, current weather, stock prices, traffic updates, and much more…
  • Datalogging: send data to the cloud to save your data online;
  • Remote control of your Raspberry Pi Pico: by interacting with IoT platforms like Adafruit IO, Node-RED, and others—you can interact with your board remotely by exchanging data via HTTP requests;
  • Interact with third-party services to send notifications: SMS, emails, notifications, and much more…

Technical Overview of HTTP Requests

Let’s take a quick look at the technical aspects of HTTP requests. If this is your first time dealing with HTTP requests in a technical manner and it seems confusing, that’s perfectly normal.

But, don’t worry, there are MicroPython modules that abstract all the technical stuff, making it very straightforward to make and handle HTTP requests. Additionally, for more information about the technical aspects of HTTP requests, we recommend the following resources:

HTTP Requests   

HTTP request consists of several parts. The main elements are: request line, headers, and body.

Request Line

The request line specifies the HTTP method, the resource being requested (the URL), and the version of the HTTP protocol being used. Common HTTP methods include GET, POST, PUT, and DELETE. For example:

GET /path/to/resource HTTP/1.1

Headers

Headers provide information about the request. It can include the host to which the client is sending the request, the type of content being sent or accepted, the user‑agent (identifies the client making the request), and more. For example:

Host: example.com
User-Agent: RaspberryPiPico
Accept: application/json

Body

The body is an optional content, and it contains data or information that we want to send to the server. This is used in POST and PUT requests. For example:

POST /submit-form HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=johndoe&password=secretpassword

HTTP Request Methods

The choice of HTTP method in a request indicates the intended action to be performed on the server. Some commonly used methods include:

  • GET: retrieve data from the server.
  • POST: submit data to be processed to a specified resource.
  • PUT: update a resource on the server.
  • DELETE: remove a resource from the server.

In this tutorial, we’ll focus on using GET requests with the Raspberry Pi Pico.

HTTP Status Codes

After receiving an HTTP request, the server responds with an HTTP status code indicating the outcome of the request. Status codes fall into categories such as 2xx (successful), 3xx (redirection), 4xx (client error), and 5xx (server error). Some of the most common:

  • 200 OK: the request was successful.
  • 404 Not Found: the requested resource could not be found.

HTTP Requests with the Raspberry Pi Pico

The easiest way to make HTTP requests with the Raspberry Pi Pico is by using the requests library, which uses a high-level approach. This is very similar to the Python requests library but is more limited.

You can also use the socket module, but it’s a more low-level approach and is not so beginner-friendly.

The following code is a basic example of how you can make a simple HTTP request to Google Website using the requests library.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details: https://RandomNerdTutorials.com/raspberry-pi-pico-w-http-requests-micropython/
 
import network
import requests

# Wi-Fi credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

# Connect to network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

# Connect to your network
wlan.connect(ssid, password)

# Make GET request
response = requests.get("http://www.google.com")
# Get response code
response_code = response.status_code
# Get response content
response_content = response.content

# Print results
print('Response code: ', response_code)
print('Response content:', response_content)

View raw code

How the Code Works

Start by including the network and the requests library.

import network
import requests

Replace ‘REPLACE_WITH_YOUR_SSID‘ and ‘REPLACE_WITH_YOUR_PASSWORD‘ with your Wi-Fi network name (SSID) and password.

ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

Then, initialize the Wi-Fi interface, activate it, and connect to your network using the SSID and password defined earlier.

# Connect to network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
# Connect to your network
wlan.connect(ssid, password)

Finally, make the request. Using the requests module and the get() method, the code sends a GET request to the Google website. The response from the server is stored in the response variable.

response = requests.get("http://www.google.com")

The response is an object of type Response. This object has several attributes that you can access and might be useful. For example:

  • response.status_code: returns an integer value representing the status of the response;
  • response.content: returns the actual content in bytes;
  • response.text: returns the content converted to a string, using a character encoding such as UTF-8;
  • response.json(): returns the response as a JSON object (dictionary);
  • response.headers(): access information about the response’s headers.

After getting the response, we get the status of the response using the status_code attribute.

response_code = response.status_code

We save the content of the response in the response_content variable using the content attribute.

response_content = response.content

Finally, we print the status code and request content to the Shell.

print('Response code: ', response_code)
print('Response content:', response_content)

Testing the Code

After inserting your network credentials, you can run the previous code on your Raspberry Pi Pico.

If everything goes as expected, the response code should be 200, and it will print the content of the Google web page.

Raspberry Pi Pico Google HTTP GET Request

Getting Data from the Web Using HTTP GET Requests

Now that you know how to make a basic HTTP GET request, we’ll show you different examples to get data from the internet. We’ll build two different examples:

Example 1: Weather Forecaster

In this example, we’ll use the Weather API to create a weather forecaster. This API is free and provides useful information about the weather in almost any location in the world.

Weather forecaster example

We’ll get the weather data for your location and display it on the shell.

Getting Your API Key

  1. Go to the Weather API website: https://www.weatherapi.com/
  2. Signup to create an account.
  3. After verifying your account, login into your account.
  4. On your dashboard at https://www.weatherapi.com/my/ , you’ll find your API key (even though it says the trial will end, you can continue using your API key freely).
Weather API Key

Copy the API key to a safe place because you’ll need it later.

To pull information on the weather in your chosen location, enter the following URL on your web browser, but inserting your location and API key on the right places:

https://api.weatherapi.com/v1/current.json?q=YOUR_LOCATION+&key=YOUR_API_KEY'

For example, in my case:

https://api.weatherapi.com/v1/current.json?q=Oporto+&key=d1578a064b07453c917164350240106'

Copy your URL and paste it into your browser, and the API will return information corresponding to your local weather. For example:

{
  "location": {
    "name": "Oporto",
    "region": "Porto",
    "country": "Portugal",
    "lat": 41.15,
    "lon": -8.62,
    "tz_id": "Europe/Lisbon",
    "localtime_epoch": 1719843562,
    "localtime": "2024-07-01 15:19"
  },
  "current": {
    "last_updated_epoch": 1719843300,
    "last_updated": "2024-07-01 15:15",
    "temp_c": 22.3,
    "temp_f": 72.1,
    "is_day": 1,
    "condition": {
      "text": "Sunny",
      "icon": "//cdn.weatherapi.com/weather/64x64/day/113.png",
      "code": 1000
    },
    "wind_mph": 10.5,
    "wind_kph": 16.9,
    "wind_degree": 310,
    "wind_dir": "NW",
    "pressure_mb": 1021,
    "pressure_in": 30.15,
    "precip_mm": 0,
    "precip_in": 0,
    "humidity": 69,
    "cloud": 0,
    "feelslike_c": 24.7,
    "feelslike_f": 76.4,
    "windchill_c": 21.9,
    "windchill_f": 71.5,
    "heatindex_c": 24.6,
    "heatindex_f": 76.2,
    "dewpoint_c": 15,
    "dewpoint_f": 58.9,
    "vis_km": 10,
    "vis_miles": 6,
    "uv": 6,
    "gust_mph": 15.4,
    "gust_kph": 24.7
  }
}

Code – HTTP GET Request: Weather API

The following code makes a request to the Weather API to get weather data on your location. Then, we display the data on the shell. We’ll display information about the current weather, temperature, humidity, and rain.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details: https://RandomNerdTutorials.com/raspberry-pi-pico-w-http-requests-micropython/

import network
import time
import requests

# Wi-Fi credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

api_key = 'REPLACE_WITH_YOUR_API_KEY'
location ='Oporto'

# Request URL
url = f'https://api.weatherapi.com/v1/current.json?q={location}+&key={api_key}'

def init_wifi(ssid, password):# Init Wi-Fi Interface
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    # Connect to your network
    wlan.connect(ssid, password)
    # Wait for Wi-Fi connection
    connection_timeout = 10
    while connection_timeout > 0:
        if wlan.status() >= 3:
            break
        connection_timeout -= 1
        print('Waiting for Wi-Fi connection...')
        time.sleep(1)
    # Check if connection is successful
    if wlan.status() != 3:
        return False
    else:
        print('Connection successful!')
        network_info = wlan.ifconfig()
        print('IP address:', network_info[0])
        return True

if init_wifi(ssid, password):
    try:
        # Make the request
        response = requests.get(url)
        #Print the response code
        print('Response code: ', response.status_code)
        
        # Get response content
        weather = response.json()
        # Close the request
        response.close()
        
        # Print bulk weather data
        print('Weather JSON: ', weather)
        
        # Get specific weather data
        weather_description = weather['current']['condition']['text']
        print('Current weather: ', weather_description)
        
        # Temperature and humidity
        temperature_c = weather['current']['temp_c']
        temperature_f = weather['current']['temp_f']
        humidity = weather['current']['humidity']
        print(f'Temperature in Celsius: {temperature_c:.2f}')
        print(f'Temperature in Fahrenheit: {temperature_f:.2f}')
        print(f'Humidity (%): {humidity:.2f}')              
        
        # Precipitation
        precipitation = weather['current']['precip_mm']
        print(f'Precipitation in mm: {precipitation}')              
        
        # Wind
        wind_speed = weather['current']['wind_kph']
        print('Wind speed in kph:', wind_speed)

    except Exception as e:
        # Handle any exceptions during the request
        print('Error during request:', e)

View raw code

How the Code Works

Let’s take a quick look at how this code works.

To make the code work, first, you need to insert your network credentials to connect your Raspberry Pi Pico to the internet.
# Wi-Fi credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

Then, insert your Weather API key, and the city from where you want to get the data.

api_key = 'REPLACE_WITH_YOUR_API_KEY'
city = 'REPLACE_WITH_YOUR_CITY'

We save the request URL on the url variable. This is an f string with placeholders so that the URL is updated with your details at run time.

url = f'https://api.weatherapi.com/v1/current.json?q={location}+&key={api_key}'

We create a function called init_wifi() that connects to your local network. This function returns True if connecting to Wi-Fi was successful or False, if it wasn’t.

def init_wifi(ssid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    # Connect to your network
    wlan.connect(ssid, password)
    # Wait for Wi-Fi connection
    connection_timeout = 10
    while connection_timeout > 0:
        if wlan.status() >= 3:
            break
        connection_timeout -= 1
        print('Waiting for Wi-Fi connection...')
        time.sleep(1)
    # Check if connection is successful
    if wlan.status() != 3:
        return False
    else:
        print('Connection successful!')
        network_info = wlan.ifconfig()
        print('IP address:', network_info[0])
        return True

Then, we connect to Wi-Fi and check if we succeed before making the request.

if init_wifi(ssid, password):

Making the request is as simple as using the get() method of the requests module and passing the URL as an argument.

response = requests.get(url)

This will return a JSON object. So, we can convert the result into a Python dictionary using the json() method.

weather = response.json()

Then, we close the connection to release any resources.

# Close the request
response.close()

Now, we have all the data you’ve seen on your web browser on the previous steps saved on the weather variable.

You access specific information by using the keys of the data you want to get. We get weather description, temperature, humidity, precipitation and wind speed. You can also get other properties by accessing the corresponding keys on the JSON object.

# Get specific weather data
weather_description = weather['current']['condition']['text']
print('Current weather: ', weather_description)
        
# Temperature and humidity
temperature_c = weather['current']['temp_c']
temperature_f = weather['current']['temp_f']
humidity = weather['current']['humidity']
print(f'Temperature in Celsius: {temperature_c:.2f}')
print(f'Temperature in Fahrenheit: {temperature_f:.2f}')
print(f'Humidity (%): {humidity:.2f}')              
        
# Precipitation
precipitation = weather['current']['precip_mm']
print(f'Precipitation in mm: {precipitation}')              
        
# Wind
wind_speed = weather['current']['wind_kph']
print('Wind speed in kph:', wind_speed)

Testing the Code

After inserting your network credentials, API key and city, you can run the code on your Raspberry Pi Pico.

You should get something similar to in the screenshot below but with the information for your chosen location.

Getting Weather Data from the Weather API using Raspberry Pi Pico

You can take this project further by displaying the data on a display, like an LCD or OLED display. You can create a while loop or a timer interrupt to request data periodically, or you can even request data for multiple locations just by changing the value of the city variable.

We have some tutorials that you can find useful:

Example 2: Request Bitcoin Price

Bitcoin logo

In this example, we’ll request and display the current Bitcoin price. CoinGecko has an endpoint that you can use to make requests that returns the current Bitcoin price in USD:

https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd

If you open that URL on your web browser, you should get something as follows:

{"bitcoin":{"usd":62748}}

Now, using that URL, we can easily get the Bitcoin price using our Raspberry Pi Pico.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details: https://RandomNerdTutorials.com/raspberry-pi-pico-w-http-requests-micropython/
 
import network
import requests
from time import sleep

# Wi-Fi credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

# Request URL
url = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd'

def init_wifi(ssid, password):# Init Wi-Fi Interface
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    # Connect to your network
    wlan.connect(ssid, password)
    # Wait for Wi-Fi connection
    connection_timeout = 10
    while connection_timeout > 0:
        if wlan.status() >= 3:
            break
        connection_timeout -= 1
        print('Waiting for Wi-Fi connection...')
        sleep(1)
    # Check if connection is successful
    if wlan.status() != 3:
        return False
    else:
        print('Connection successful!')
        network_info = wlan.ifconfig()
        print('IP address:', network_info[0])
        return True

if init_wifi(ssid, password):
    try:
        # Make the request
        response = requests.get(url)
        #Print the response code
        print('Response code: ', response.status_code)
        
        # Get response content
        bitcoin = response.json()
        # Close the request
        response.close()
        
        # Print bitcoin price
        bitcoin_price = bitcoin['bitcoin']['usd']
        print('Bitcoin price (USD): ', bitcoin_price)

    except Exception as e:
        # Handle any exceptions during the request
        print('Error during request:', e)

View raw code

This code works in a similar way to the one in the previous example.

Raspberry Pi Pico MicroPython HTTP GET Request Bitcoin Price

Taking It Further

Now, you can take this project further and display the bitcoin price on an OLED or LCD and update the data every day. You can also request data for different cryptocurrencies.

You can also add some sort of notification that will send you a message when the price crosses a certain threshold value.

Wrapping Up

In this tutorial, you learned about HTTP GET requests and why they are useful. We’ve also shown you two different examples to get data from the internet.

We hope you found this tutorial useful. We have more Raspberry Pi Pico tutorials that you may like:

If you want to learn more about the Raspberry Pi Pico, make sure to take a look at our resources:



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

7 thoughts on “Raspberry Pi Pico W: Getting Started with HTTP GET Requests (MicroPython)”

  1. I use: MicroPython v1.19.1-88-g74e33e714 on 2022-06-30; Raspberry Pi Pico W with RP2040.
    I don’t know how to install the module: requests.

    MPY: soft reboot
    Traceback (most recent call last):
    File “”, line 5, in
    ImportError: no module named ‘requests’

    Reply
    • Hi.
      That module is included by default.
      Make sure you installed the latest MicroPython firmware for the Raspberry Pi Pico W version.
      If you mistakenly installed for the RPi Pico (without the W—without wireless capabilities), it won’t have the requests module by default.

      Regards,
      Sara

      Reply
  2. When I run the first

    Make GET request

    response = requests.get(“http://www.google.com”)

    I get the following error:
    Traceback (most recent call last):
    File “”, line 38, in
    File “requests/init.py”, line 182, in get
    File “requests/init.py”, line 76, in request
    OSError: -2

    where line 38 is the GET request.
    What’s causing this? I just copied the code out of the example.

    Reply
    • Hi.
      Did you insert your network credentials in the code?
      Are you using a Raspberry Pi Pico W (W – means it supports Wi-Fi.)
      Did you flash it with firmware for the Pico W??

      Regards,
      Sara

      Reply
      • Yes, I had done all that you pointed out. I had been doing the examples from the first tutorial without any problems so I knew my Pico was running fine.

        I did fix the problem by going into Thonny and having it reload “responses” and that fixed the problem. I’d still like to know what the error message indicated.

        Thanks for the quicfk response.

        Reply
  3. Hi,
    Thanks for this tutorial.
    I have been able to run the basic script to query google.com, but I wanted to do something a bit more advanced.
    I want to be able to send information from one pico to another wirelessly.
    So using another of your tutorials I setup a web server on one pico and using this script I just wanted to query the web page displayed on the other pico.
    I have the web server up and running and I am able to display the page on my pc but when I try to query the page on the pico I get the following

    Traceback (most recent call last):
    File “”, line 41, in
    File “requests/init.py”, line 201, in get
    File “requests/init.py”, line 94, in request
    OSError: [Errno 103] ECONNABORTED

    Using your function ‘init_wifi’ I was able to confirm the pico is connecting to the correct wireless network, but just won’t display the page

    Do you have any suggestions

    Thanks
    Mel

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.