Raspberry Pi Pico W
Using A JSON API

There are lots of web servers that have APIs that use the JSON format. JSON, JavaScript Object Notation is a standard format for sharing data. There are loads of free APIs that you can use. This first program is a basic test showing how you connect and retrieve individual values from the JSON you download.

from time import sleep
from network import WLAN, STA_IF
from secrets import secrets
from urequests import get

wlan = WLAN(STA_IF)

def connect():
    wlan.active(True)
    wlan.config(pm = 0xa11140)
    wlan.connect(secrets["ssid"], secrets["password"])

    # try to connect or fail
    max_wait = 10
    while max_wait >0:
        if wlan.status() <0 or wlan.status()>=3:
            break
        max_wait -= 1
        print("Waiting for connection...")
        sleep(1)

    # connection error
    if wlan.status() != 3:
        return False
    else:
        status = wlan.ifconfig()
        print("Connected to", secrets["ssid"], "on", status[0])
        print()
        return True

if not connect():
    print("Couldn't connect to WiFi.")
else:
    print("Success.")
    print()
    TEXT_URL = "http://date.jsontest.com"
    while True:  
        r = get(TEXT_URL)
        d = r.json()
        # print the whole object
        print(d)
        print(d["date"], d["time"])
        r.close() # must close the response
        sleep(60)

This next program needs you to sign up for a free account on https://openweathermap.org/. You then need to generate a token to use in your API requests. Once you have done this, update your secrets file with the token and the latitude and longitude of the location whose weather data you wish to download.

secrets = {
    'ssid' : 'YOUR SSID',
    'password' : 'YOUR WIFI PASSWORD',    
    'owm_token' : 'OPEN WEATHER MAP TOKEN',
    'lat' : "YOUR LATITUDE",
    'long' : "YOUR LONGITUDE"
    }

This is the main program that makes the API request and extracts the data.

from time import sleep
from network import WLAN, STA_IF
from secrets import secrets
from urequests import get

wlan = WLAN(STA_IF)

def connect():
    wlan.active(True)
    wlan.config(pm = 0xa11140)
    wlan.connect(secrets["ssid"], secrets["password"])

    # try to connect or fail
    max_wait = 10
    while max_wait >0:
        if wlan.status() <0 or wlan.status()>=3:
            break
        max_wait -= 1
        print("Waiting for connection...")
        sleep(1)

    # connection error
    if wlan.status() != 3:
        return False
    else:
        status = wlan.ifconfig()
        print("Connected to", secrets["ssid"], "on", status[0])
        print()
        return True

if not connect():
    print("Couldn't connect to WiFi.")
else:
    print("Success.")
    print()
    owm_url = "https://api.openweathermap.org/data/2.5/weather?lat=" + secrets["lat"]
    owm_url += "&lon=" + secrets["long"] + "&appid=" + secrets["owm_token"]
    r = get(owm_url)
    d = r.json()
    print("-" * 40)
    print("JSON In Full")
    print("-" * 40)
    print(d)
    print()
    print("-" * 40)
    print("Just The Data We Want")
    print("-" * 40)
    temp = d["main"]["temp"] - 273.15
    humidity = d["main"]["humidity"]
    pressure = d["main"]["pressure"]
    weather_main = d["weather"][0]["main"]
    weather_desc = d["weather"][0]["description"]
    print("Weather Data")
    print("------------")
    print()
    print("Temperature:", round(temp,2), "Celsius")
    print(weather_main, weather_desc, sep=", ")
    print("Humidity: ", humidity, "%", sep="")
    print("Pressure: ", pressure, "hPa", sep="")
    r.close()
    wlan.disconnect()
    print("Disconnected.")

This last program works quite nicely. There is a load of data that can be retrieved. Check out the OpenWeatherMap site for more details on how to vary your API request.

You can find loads of other free APIs that you can use. Not all of the sites using https worked for me. According to the documentation for the Pico W, you can use https but SSL won't work for you. You should also make sure to close your requests when getting information from web sites to avoid memory issues on the Pico W.