Testing an HTTP GET Request
Welcome to HTTP GET!
In this lab you will ask the internet for real live data. Your Pico W will find out how many people are in space right now!
When your browser loads a webpage, it uses a request called Hypertext Transfer Protocol (HTTP). HTTP is the language that computers use to ask for and share information on the web. An HTTP GET request is how you ask a web server to send you some data.
In this lab you will send an HTTP GET request to a free website that tracks how many people are currently in space. The website sends back data in a format called JavaScript Object Notation (JSON). JSON is a way to organize data using labels and values, like a dictionary.
The Code
This example was inspired by Tom's Hardware.
Make sure you have your secrets.py file set up from the previous lab before running this code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
What each line does:
import urequests— loads the MicroPython library for making web requestsurequests.get(url)— sends an HTTP GET request to the given web address.json()— converts the text response into a Python dictionaryastronauts['number']— reads the value with the key'number'from the dictionaryastronauts['people'][i]['name']— reads the name of the i-th person in the list
Key Idea
JSON data looks like a Python dictionary. You read values using keys in square brackets, like data['key']. Once you know this, you can read data from almost any website!
Expected Output
1 2 3 4 5 6 7 8 9 10 11 12 | |
The exact names and count will change because real astronauts rotate in and out of the International Space Station!
The request took about 786 milliseconds — less than one second. That is how fast the internet can deliver data to your tiny Pico W.
Amazing!
Your Pico W just fetched live data from the internet! In the next lab, you will flip it around and turn your Pico W into a web server so other devices can connect to it.