Lesson 10
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.
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.

The principle boils down to four steps, which will come back in every program in this lesson:
Every HTTP request carries a method, which indicates the client's intent. The two most common ones are:
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.
-1 signals a refused connection and-11 a read timeout.Most APIs answer in JSON ("JavaScript Object Notation"), a text format that describes data as key-value pairs. Here is an example response:
{
"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.
"Paris".14.2.true orfalse, without quotation marks.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.
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.

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.
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.
#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.
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.
#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¤t=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().

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.
const char* url =
"https://api.open-meteo.com/v1/forecast?latitude=48.85&longitude=2.35"
"¤t=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.
doc["city"].doc["current"]["temperature_2m"].doc["forecast"][0].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"].
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.
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.
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.
#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.
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:
WiFi.status() is indeedWL_CONNECTED before sending a request.deserializeJson() before reading the fields.http.end(): memory fills up little by little and the board eventually crashes.delay() ormillis(): the server blocks you (code 429).deserializeJson().temperature instead oftemperature_2m: the result is then zero, with no error message.http:// instead ofhttps:// with an API that requires encryption.HTTPClient.deserializeJson() reads a JSON text andserializeJson() builds one.http.end().Exercise