Esp32 Tutorial: WiFi + API Requests

0 - Introduction

With almost every IoT project you might need to access an API, either to send or receive data, in this article, we will make an API call to openweathermap to get the current weather for a given location.

1 - Code

Let’s start with the defines and variables, you will need an API key for openweathermap, which is free to get, you can then copy the url template we will use, create two string variables, one for your WiFi ssid and on for your password, and then, for includes, we will need Arduino, stdio for snprintf, WiFi to connect to your network and HTTPClient to make the API call:

#define OPENWEATHERMAP_API_KEY "inputyourapikeyhere"
#define OPENWEATHERMAP_CURRENT_WEATHER "https://api.openweathermap.org/data/2.5/weather?lat=%lf&lon=%lf&appid=%s"

#include <Arduino.h>
#include <stdio.h>

#include <WiFi.h>
#include <HTTPClient.h>

const char* wifi_ssid = "";
const char* wifi_pass = "";

On init WiFi, begin WiFi with your ssid and password and wait until it connects, if it doesn’t connect, then you will be stuck in this loop forever and will need to reboot the Esp. All ‘Serial.println’s are optional:

void initWiFi()
{
    WiFi.begin(wifi_ssid, wifi_pass);
    Serial.println("Connecting...");
    while (WiFi.status()!= WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected with address: ");
    Serial.println(WiFi.localIP());
}

Now for the API Call, create a buffer for the url, using snprintf populate the fields of the url with the latitude, longitude and your API key. If WiFi is not connected, return an empty JSON object. Create the http client and begin it, make a GET request, if you get an error, return an empty JSON object, if you don’t get errors, get the response as string, end the http client and return the response:

String getCurrentWeather(double lat, double lon)
{
    char url[150];
    sprintf(url, OPENWEATHERMAP_CURRENT_WEATHER, lat, lon, OPENWEATHERMAP_API_KEY);
    if (WiFi.status() != WL_CONNECTED)
        return "{}";
    HTTPClient http;
    http.begin(url);
    int resp = http.GET();
    if (resp <= 0)
        return "{}";
    String data = http.getString();
    http.end();
    return data;
}

On setup, begin the Serial, intialize the WiFi connection and make the API call, then log it’s results and that’s it!

void setup()
{
    // put your setup code here, to run once:
    Serial.begin(115200);
    initWiFi(); // connect to wifi

    String data = getCurrentWeather(51.5072, 0.1276); // London
    Serial.println(data);
}

Even if we don’t use the ‘loop’ function, it still needs to be present:

void loop() { }

And that’s it. Thanks for reading and stay tuned for more tech insights and tutorials. Until next time, and keep exploring the world of tech!