Lesson 10 / 1191%

Lesson 10

HTTP Requests and JSON

25 min

Query a web API with HTTPClient, parse JSON with ArduinoJson and send data with POST.

Definition

An HTTP client is a program that sends requests to a server and reads its response. A web API ("Application Programming Interface") is an online service that answers these requests with data rather than with pages to display. This data is most often written in JSON format, a text format that describes information as key-value pairs. On an ESP32, the HTTP client lets you retrieve information from the Internet (weather, time, a currency's exchange rate) or send your own measurements to a server.

The ESP32 as a client

In the previous lesson, the ESP32 received requests. It can alsosend them: it then plays the role of a client, like a browser, and can query a service on the Internet to retrieve information (weather, time, a currency's exchange rate...) or send its own measurements to a server. This is done through web APIs, which answer with data rather than with pages.

The roles are therefore reversed compared with the web server lesson. There, the board waited for a browser to come to it. Here, it is the board that takes the initiative: it contacts a remote server, asks a question and waits for the answer. For this to work, the board must be connected to a network that has Internet access, and not just to a local network.

Diagram: the ESP32 sending a GET request to an API on the Internet, and receiving data in JSON format in return.

The principle boils down to four steps, which will come back in every program in this lesson:

  • Step 1: the board connects to Wi-Fi.
  • Step 2: it sends an HTTP request to the API's address.
  • Step 3: it checks the response code, then reads the text returned by the server.
  • Step 4: it extracts the useful values from that text (the JSON) and uses them, for example to display them or turn on an LED.

HTTP methods

Every HTTP request carries a method, which indicates the client's intent. The two most common ones are:

  • GET: ask for a resource (read data).
  • POST: send data to the server (for example a measurement).

There are other methods, such as PUT (modify a resource) and DELETE (delete one), but GET and POST are enough for the vast majority of projects. A good way to remember them: with GET, you read; with POST, you write.

The response contains a status code: 200 means everything went well, 404 means the resource doesn't exist, 500 means an error occurred on the server side. A negative code returned by the library indicates a connection problem.

  • 200: success, the response contains the requested data.
  • 401 or 403: access denied, an API key or some authorization is probably required.
  • 404: the address doesn't exist, check the spelling of the URL.
  • 429: too many requests, you must space out your calls.
  • 500 or 503: the problem comes from the server, not from your code. Try again later.
  • Negative value: the library could not reach the server (no Wi-Fi, unreachable server, timeout). For example,-1 signals a refused connection and-11 a read timeout.

The JSON format

Most APIs answer in JSON ("JavaScript Object Notation"), a text format that describes data as key-value pairs. Here is an example response:

JSON example
{
  "city": "Paris",
  "temperature": 14.2,
  "rain": false,
  "forecast": [12.1, 13.5, 11.8]
}

This text is readable by humans as well as by programs. Curly braces delimit an object, that is, a set of fields. Each field associates a key, written between quotation marks ("city"), with a value. Square brackets delimit an array, that is, an ordered list of values.

  • Text: between double quotation marks, for example"Paris".
  • Number: without quotation marks, an integer or a decimal with a dot, for example 14.2.
  • Boolean: true orfalse, without quotation marks.
  • Array: a list between square brackets, with values separated by commas.
  • Object: a group of fields between curly braces. Objects can be nested inside one another.

A strict syntax

JSON is very strict: keys and text must use doublequotation marks (never single ones), and there must be no comma after the last element. A single mistake makes the whole document unreadable for the library.

Installing the ArduinoJson library

To read JSON, we use the very popular ArduinoJson library by Benoît Blanchon. Open the IDE's Library Manager (the books icon in the sidebar), search for "ArduinoJson" and install it.

Screenshot: the Arduino IDE Library Manager with ArduinoJson searched and the Install button.

The examples in this lesson use version 7 of ArduinoJson, in which the document is declared with JsonDocument. Older tutorials used StaticJsonDocument orDynamicJsonDocument with a size to specify: if you copy old code and get an error or a warning, that is probably the reason.

Reading JSON offline to practice

Before querying a real API, it is simpler to practice with a JSON text written directly in the program. This lets you understand how fields are read without worrying about Wi-Fi or the server. TheR"json( and )json" markers let you write the text as is, with its quotation marks.

read_json.ino
#include <ArduinoJson.h>

const char* text = R"json({"city":"Paris","temperature":14.2,"rain":false,"forecast":[12.1,13.5,11.8]})json";

void setup() {
  Serial.begin(115200);

  JsonDocument doc;
  DeserializationError error = deserializeJson(doc, text);

  if (error) {
    Serial.print("Unreadable JSON: ");
    Serial.println(error.c_str());
    return;
  }

  const char* city = doc["city"];
  float temperature = doc["temperature"];
  bool rain = doc["rain"];
  float first = doc["forecast"][0];
  int count = doc["forecast"].size();

  Serial.println(city);
  Serial.println(temperature);
  Serial.println(rain ? "It is raining" : "It is not raining");
  Serial.print("First forecast: ");
  Serial.println(first);

  Serial.print("There are ");
  Serial.print(count);
  Serial.println(" forecasts:");
  for (JsonVariant v : doc["forecast"].as<JsonArray>()) {
    Serial.println(v.as<float>());
  }
}

void loop() {
}

The deserializeJson() function "deserializes" the text: it turns it into a document the program knows how to query. If the text is malformed, it returns an error, which you can print witherror.c_str(). Once the document is built, you read values with square brackets, as in an array.

Querying a weather API

The following example queries the free Open-Meteo API, which requires no access key, to retrieve the current temperature in Paris. Since this API uses HTTPS (an encrypted connection), we use a secure client.

Before writing the code, here is a valuable tip: paste the API's address into your browser's address bar. You will directly see the JSON returned, with the exact names of the fields. This saves you from guessing the structure of the response and lets you spot mistakes in the address before uploading anything.

weather.ino
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "MyNetworkName";
const char* password = "MyPassword";

const char* url =
  "https://api.open-meteo.com/v1/forecast?latitude=48.85&longitude=2.35&current=temperature_2m";

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("Connected to Wi-Fi");
}

void loop() {
  WiFiClientSecure client;
  client.setInsecure();   // no certificate verification (see note)

  HTTPClient http;
  http.begin(client, url);
  int code = http.GET();

  if (code == 200) {
    String response = http.getString();

    JsonDocument doc;
    DeserializationError error = deserializeJson(doc, response);

    if (!error) {
      float temperature = doc["current"]["temperature_2m"];
      Serial.print("Temperature in Paris: ");
      Serial.print(temperature);
      Serial.println(" C");
    } else {
      Serial.println("Unreadable JSON response");
    }
  } else {
    Serial.print("HTTP error: ");
    Serial.println(code);
  }

  http.end();
  delay(60000);   // one request per minute is plenty
}

The program follows the four steps described above. Insetup(), the board connects to Wi-Fi. Inloop(), http.begin() prepares the request, http.GET() sends it and returns the response code, then http.getString() retrieves the text. Finally, http.end() frees the resources: never forget it, otherwise the board's memory eventually fills up.

About setInsecure()

client.setInsecure() does encrypt the connection, but does not verify the server's identity. It is convenient for learning, but should be avoided as soon as the data exchanged is sensitive: you then need to provide the server's root certificate withclient.setCACert().

Screenshot: the serial monitor showing "Temperature in Paris: 14.2 C" with the value refreshed every minute.

Reading several values and providing default values

The Open-Meteo API can return several measurements at once: you just list them, separated by commas, in the current parameter of the address. In the following example, we retrieve the temperature, the humidity and the wind speed. The | operator provides a default value when a field is missing from the response, which avoids misleading zeros or crashes.

full_weather.ino
const char* url =
  "https://api.open-meteo.com/v1/forecast?latitude=48.85&longitude=2.35"
  "&current=temperature_2m,relative_humidity_2m,wind_speed_10m";

void readWeather() {
  WiFiClientSecure client;
  client.setInsecure();

  HTTPClient http;
  http.setTimeout(10000);   // give up after 10 seconds
  http.begin(client, url);
  int code = http.GET();

  if (code == 200) {
    JsonDocument doc;
    DeserializationError error = deserializeJson(doc, http.getString());

    if (!error) {
      float temperature = doc["current"]["temperature_2m"] | -99.0;
      int humidity = doc["current"]["relative_humidity_2m"] | -1;
      float wind = doc["current"]["wind_speed_10m"] | -1.0;

      Serial.print("Temperature: ");
      Serial.print(temperature);
      Serial.println(" C");
      Serial.print("Humidity: ");
      Serial.print(humidity);
      Serial.println(" %");
      Serial.print("Wind: ");
      Serial.print(wind);
      Serial.println(" km/h");
    } else {
      Serial.print("Unreadable JSON: ");
      Serial.println(error.c_str());
    }
  } else {
    Serial.print("Error: ");
    Serial.println(code);
    if (code < 0) {
      Serial.println(HTTPClient::errorToString(code));
    }
  }

  http.end();
}

Three good practices appear in this code. First,http.setTimeout() sets a maximum delay: without it, the board can stay blocked for a long time if the server doesn't answer. Next, the default values (-99, -1) are deliberately impossible for a real measurement: you immediately recognize that a piece of data was missing. Finally, when the code is negative, HTTPClient::errorToString()turns it into a readable message. It only describes the library's own errors, not HTTP codes such as 404, which is why the code itself is printed in every case.

Reading JSON: the principle

  • You access a field by its key: doc["city"].
  • Nested objects are chained: doc["current"]["temperature_2m"].
  • An array is read with an index: doc["forecast"][0].
  • You always check the result of deserializeJson() before using the values.

To find your way around a complex JSON, read it like a path: starting from the root, you go down field by field until you reach the wanted value. In the weather API example, the temperature is in thecurrent object, under the key temperature_2m: the path is therefore written doc["current"]["temperature_2m"].

Sending data with POST

To transmit a measurement to a server, you send a POST request with a message body, often in JSON. The address below is fictitious: replace it with the address of your own service.

send_post.ino
void sendMeasurement(float temperature) {
  WiFiClientSecure client;
  client.setInsecure();

  HTTPClient http;
  http.begin(client, "https://example.com/api/measurements");
  http.addHeader("Content-Type", "application/json");

  JsonDocument doc;
  doc["sensor"] = "esp32-livingroom";
  doc["temperature"] = temperature;

  String body;
  serializeJson(doc, body);

  int code = http.POST(body);
  Serial.print("Server response: ");
  Serial.println(code);

  http.end();
}

Here, the direction is reversed: instead of reading JSON, you buildit. You fill a document with key-value pairs, thenserializeJson() converts it into text, which is sent as the body of the request. The Content-Type header tells the server that this text is JSON: without it, some servers reject the request.

Building a richer JSON

A JSON document can contain arrays and nested objects. With ArduinoJson, you create them with to<JsonArray>() andto<JsonObject>(). TheserializeJsonPretty() function prints the result in an airy layout, handy for checking the document in the serial monitor.

build_json.ino
#include <ArduinoJson.h>

void setup() {
  Serial.begin(115200);

  JsonDocument doc;
  doc["sensor"] = "esp32-livingroom";
  doc["active"] = true;

  JsonObject location = doc["location"].to<JsonObject>();
  location["room"] = "living room";
  location["floor"] = 1;

  JsonArray measurements = doc["measurements"].to<JsonArray>();
  measurements.add(21.5);
  measurements.add(21.7);
  measurements.add(22.0);

  serializeJsonPretty(doc, Serial);
}

void loop() {
}

Good to know

Respect the usage limits of free APIs: don't send requests in a burst, space them out by several seconds or minutes. Services may also change their format over time; check their documentation if your code stops working.

Protect your API keys

Many APIs require a personal access key, which you add to the address or to a header. Just like your Wi-Fi password, never publish this key in code shared on a forum or a public repository: someone could use it in your place and exhaust your quota.

Handling errors properly

A program that queries the Internet must always expect that it can fail: the Wi-Fi can drop, the server can be down, the response can have changed format. There are three levels of checking, to be chained in this order:

  • The Wi-Fi connection: check thatWiFi.status() is indeedWL_CONNECTED before sending a request.
  • The HTTP code: only use the response if the code is 200. Otherwise, print the code to understand the problem.
  • The JSON: test the result ofdeserializeJson() before reading the fields.

Common mistakes

  • Forgetting http.end(): memory fills up little by little and the board eventually crashes.
  • Sending requests at full speed, without delay() ormillis(): the server blocks you (code 429).
  • Reading JSON fields without checking the 200 code or the result ofdeserializeJson().
  • Getting a field name wrong, for example writingtemperature instead oftemperature_2m: the result is then zero, with no error message.
  • Using http:// instead ofhttps:// with an API that requires encryption.
  • Calling the API while the board is not connected to Wi-Fi.

Key takeaways

  • The ESP32 can be a client: it sends requests to web APIs withHTTPClient.
  • GET reads data, POST sends it. The response code 200 means everything went well.
  • JSON describes data with objects (curly braces), arrays (square brackets) and key-value pairs.
  • deserializeJson() reads a JSON text andserializeJson() builds one.
  • Always check the HTTP code and the result of the JSON parsing, and end every request with http.end().
  • Space out your requests and keep your API keys secret.

Exercise

Modify the example to query the weather of another city (find its GPS coordinates), then turn on the board's LED if the temperature exceeds 20 °C. Always check the HTTP code before reading the data. To go further, also print the humidity and the wind, and make the LED blink if the wind exceeds 30 km/h.