ESP32 HTTP GET with Arduino IDE (OpenWeatherMap.org and ThingSpeak)

In this guide, you’ll learn how to make HTTP GET requests using the ESP32 board with Arduino IDE. We’ll demonstrate how to decode JSON data from OpenWeatherMap.org and plot values in charts using ThingSpeak.

ESP32 HTTP GET with Arduino IDE OpenWeatherMap ThingSpeak

Recommended: ESP32 HTTP POST with Arduino IDE (ThingSpeak and IFTTT.com)

HTTP GET Request Method

The Hypertext Transfer Protocol (HTTP) works as a request-response protocol between a client and server. Here’s an example:

  • The ESP32 (client) submits an HTTP request to a Server (for example: OpenWeatherMap.org or ThingSpeak);
  • The server returns a response to the ESP32 (client);
  • Finally, the response contains status information about the request and may also contain the requested content.

HTTP GET

GET is used to request data from a specified resource. It is often used to get values from APIs.

For example, you can use a simple request to return a value or JSON object:

GET /weather?countryCode=PT

Additionally, you can also make a GET request to update a value (like with ThingSpeak). For example, you can use:

GET /update?field1=value1

Note that the query string (name = field1 and value = value1) is sent in the URL of the HTTP GET request.

(With HTTP GET, data is visible to everyone in the URL request.)

Prerequisites

Before proceeding with this tutorial, make sure you complete the following prerequisites.

Arduino IDE

We’ll program the ESP32 using Arduino IDE, so make sure you have the ESP32 add-on installed.

Arduino_JSON Library

You also need to install the Arduino_JSON library. You can install this library in the Arduino IDE Library Manager. Just go to Sketch Include Library > Manage Libraries and search for the library name as follows:

Install Arduino JSON library Arduino IDE

Other Web Services or APIs

In this guide, you’ll learn how to setup your ESP32 board to perform HTTP requests to OpenWeatherMap.org and ThingSpeak. If you prefer to learn with a local solution you can use HTTP with Node-RED. All examples presented in this guide also work with other APIs.

In summary, to make this guide compatible with any service, you need to search for the service API documentation. Then, you need the server name (URL or IP address), and parameters to send in the request (URL path or request body). Finally, modify our examples to integrate with any API you want to use.

1. ESP32 HTTP GET: JSON Data (OpenWeatherMap.org)

In this example you’ll learn how to make API requests to access data. As an example, we’ll use the OpenWeatherMap API. This API has a free plan and provides lots of useful information about the weather in almost any location in the world.

HTTP GET Open Weather Map ESP32

Using OpenWeatherMap API

An application programming interface (API) is a set of functions written by software developers to enable anyone to use their data or services. The OpenWeatherMap project has an API that enables users to request weather data.

OpenWeatherMap API logo

In this project, you’ll use that API to request the day’s weather forecast for your chosen location. Learning to use APIs is a great skill because it allows you access to a wide variety of constantly changing information, such as current stock prices, currency exchange rates, the latest news, traffic updates, tweets, and much more.

Note: API keys are unique to the user and shouldn’t be shared with anyone.

OpenWeatherMap’s free plan provides everything you need to complete this project. To use the API you need an API key, known as the APIID. To get the APIID:

  1. Open a browser and go to https://openweathermap.org/appid/
  2. Press the Sign up button and create a free account.
  3. Go to this link: https://home.openweathermap.org/api_keys and get your API key.
OpenWeatherMap API Key Copy
  1. On the API keys tab, you’ll see a default key (highlighted in a red rectangle in figure above); this is a unique key you’ll need to pull information from the site. Copy and paste this key somewhere; you’ll need it in a moment.
  2. To pull information on weather in your chosen location, enter the following URL:
http://api.openweathermap.org/data/2.5/weather?q=yourCityName,yourCountryCode&APPID=yourUniqueAPIkey

Replace yourCityName with the city you want data for, yourCountryCode with the country code for that city, and yourUniqueAPIkey with the unique API key from step 4. For example, the updated API URL for the city of Porto, Portugal, would be:

http://api.openweathermap.org/data/2.5/weather?q=Porto,
PT&APPID=801d2603e9f2e1c70e042e4f5f6e0---
  1. Copy your URL into your browser, and the API will return a bunch of information corresponding to your local weather. We got the following information about the weather in Porto, Portugal, on the day we wrote this tutorial.
{"coord":{"lon":-8.611,"lat":41.1496},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"stations","main":{"temp":294.58,"feels_like":294.95,"temp_min":293.82,"temp_max":295.65,"pressure":1016,"humidity":83},"visibility":10000,"wind":{"speed":8.94,"deg":180,"gust":8.94},"clouds":{"all":75},"dt":1666877635,"sys":{"type":2,"id":2009460,"country":"PT","sunrise":1666853957,"sunset":1666892227},"timezone":3600,"id":2735943,"name":"Porto","cod":200}

This is how it looks with indentation for better readability.

{
  "coord": {
    "lon": -8.611,
    "lat": 41.1496
  },
  "weather": [
    {
      "id": 803,
      "main": "Clouds",
      "description": "broken clouds",
      "icon": "04d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 294.58,
    "feels_like": 294.95,
    "temp_min": 293.82,
    "temp_max": 295.65,
    "pressure": 1016,
    "humidity": 83
  },
  "visibility": 10000,
  "wind": {
    "speed": 8.94,
    "deg": 180,
    "gust": 8.94
  },
  "clouds": {
    "all": 75
  },
  "dt": 1666877635,
  "sys": {
    "type": 2,
    "id": 2009460,
    "country": "PT",
    "sunrise": 1666853957,
    "sunset": 1666892227
  },
  "timezone": 3600,
  "id": 2735943,
  "name": "Porto",
  "cod": 200
}

Next, you’ll see how to use this information to get specific data like temperature, humidity, pressure, wind speed, etc.

Code ESP32 HTTP GET OpenWeatherMap.org

After installing the necessary board add-ons and libraries, copy the following code to your Arduino IDE, but don’t upload it yet. You need to make some changes to make it work for you.

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-open-weather-map-thingspeak-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

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

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Your Domain name with URL path or IP address with path
String openWeatherMapApiKey = "REPLACE_WITH_YOUR_OPEN_WEATHER_MAP_API_KEY";
// Example:
//String openWeatherMapApiKey = "bd939aa3d23ff33d3c8f5dd1dd435";

// Replace with your country code and city
String city = "Porto";
String countryCode = "PT";

// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES
// For a final application, check the API call limits per hour/minute to avoid getting blocked/banned
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 10 seconds (10000)
unsigned long timerDelay = 10000;

String jsonBuffer;

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

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading.");
}

void loop() {
  // Send an HTTP GET request
  if ((millis() - lastTime) > timerDelay) {
    // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&APPID=" + openWeatherMapApiKey;
      
      jsonBuffer = httpGETRequest(serverPath.c_str());
      Serial.println(jsonBuffer);
      JSONVar myObject = JSON.parse(jsonBuffer);
  
      // JSON.typeof(jsonVar) can be used to get the type of the var
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }
    
      Serial.print("JSON object = ");
      Serial.println(myObject);
      Serial.print("Temperature: ");
      Serial.println(myObject["main"]["temp"]);
      Serial.print("Pressure: ");
      Serial.println(myObject["main"]["pressure"]);
      Serial.print("Humidity: ");
      Serial.println(myObject["main"]["humidity"]);
      Serial.print("Wind Speed: ");
      Serial.println(myObject["wind"]["speed"]);
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;
    
  // Your Domain name with URL path or IP address with path
  http.begin(client, serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "{}"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

View raw code

Setting your network credentials

Modify the next lines with your network credentials: SSID and password. The code is well commented on where you should make the changes.

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Setting your OpenWeatherMap.org API Key

Insert your API key in the following like:

String openWeatherMapApiKey = "REPLACE_WITH_YOUR_OPEN_WEATHER_MAP_API_KEY";

Setting your city and country

Enter the city you want to get data for, as well as the country code in the following variables:

// Replace with your country code and city
String city = "Porto";
String countryCode = "PT";

After making these changes, you can upload the code to your board. Continue reading to learn how the code works.

HTTP GET Request (JSON Object)

In the loop(), call the httpGETRequest() function to make the HTTP GET request:

String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&APPID=" + openWeatherMapApiKey;

jsonBuffer = httpGETRequest(serverPath.c_str());

The httpGETRequest() function makes a request to OpenWeatherMap and it retrieves a string with a JSON object that contains all the information about the weather for your city.

String httpGETRequest(const char* serverName) {
  HTTPClient http;

  // Your IP address with path or Domain name with URL path 
  http.begin(serverName);

  // Send HTTP POST request
  int httpResponseCode = http.GET();

  String payload = "{}"; 

  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

Decoding JSON Object

To get access to the values, decode the JSON object and store all values in the jsonBuffer array.

JSONVar myObject = JSON.parse(jsonBuffer);
// JSON.typeof(jsonVar) can be used to get the type of the var

if (JSON.typeof(myObject) == "undefined") {
  Serial.println("Parsing input failed!");
  return;
}

Serial.print("JSON object = ");
Serial.println(myObject);
Serial.print("Temperature: ");
Serial.println(myObject["main"]["temp"]);
Serial.print("Pressure: ");
Serial.println(myObject["main"]["pressure"]);
Serial.print("Humidity: ");
Serial.println(myObject["main"]["humidity"]);
Serial.print("Wind Speed: ");
Serial.println(myObject["wind"]["speed"]);

HTTP GET Demonstration

After uploading the code, open the Serial Monitor and you’ll see that it’s receiving the following JSON data:

{"coord":{"lon":-8.61,"lat":41.15},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":294.44,"feels_like":292.82,"temp_min":292.15,"temp_max":297.04,"pressure":1008,"humidity":63},"visibility":10000,"wind":{"speed":4.1,"deg":240},"clouds":{"all":20},"dt":1589288330,"sys":{"type":1,"id":6900,"country":"PT","sunrise":1589260737,"sunset":1589312564},"timezone":3600,"id":2735943,"name":"Porto","cod":200}

Then, it prints the decoded JSON object in the Arduino IDE Serial Monitor to get the temperature (in Kelvin), pressure, humidity and wind speed values.

ESP32 ESP8266 NodeMCU HTTP GET with Arduino IDE OpenWeatherMap Response

For demonstration purposes, we’re requesting new data every 10 seconds. However, for a long term project you should increase the timer or check the API call limits per hour/minute to avoid getting blocked/banned.

2. ESP32 HTTP GET: Update Value (ThingSpeak)

In this example, the ESP32 makes an HTTP GET request to update a reading in ThingSpeak.

HTTP GET ThingSpeak ESP32

Using ThingSpeak API

ThingSpeak has a free API that allows you to store and retrieve data using HTTP. In this tutorial, you’ll use the ThingSpeak API to publish and visualize data in charts from anywhere. As an example, we’ll publish random values, but in a real application you would use real sensor readings.

To use ThingSpeak with your ESP, you need an API key. Follow the next steps:

  1. Go to ThingSpeak.com and create a free account.
  2. Then, open the Channels tab.
  3. Create a New Channel.
ESP32 ESP8266 NodeMCU ThingSpeak Create New Channel
  1. Open your newly created channel and select the API Keys tab to copy your Write API Key.
ESP32 ESP8266 NodeMCU ThingSpeak View API Key Write Copy

Code ESP32 HTTP GET ThingSpeak

Copy the next sketch to your Arduino IDE (type your SSID, password, and API Key):

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-open-weather-map-thingspeak-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

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

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// REPLACE WITH THINGSPEAK.COM API KEY
String serverName = "http://api.thingspeak.com/update?api_key=REPLACE_WITH_YOUR_API_KEY";
// EXAMPLE:
//String serverName = "http://api.thingspeak.com/update?api_key=7HQJM49R8JAPR";

// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES
// For a final application, check the API call limits per hour/minute to avoid getting blocked/banned
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 10 seconds (10000)
unsigned long timerDelay = 10000;

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

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading.");
  
  // Random seed is a number used to initialize a pseudorandom number generator
  randomSeed(analogRead(33));
}

void loop() {
  // Send an HTTP GET request
  if ((millis() - lastTime) > timerDelay) {
    // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      WiFiClient client;
      HTTPClient http;

      String serverPath = serverName + "&field1=" + String(random(40));
      
      // Your Domain name with URL path or IP address with path
      http.begin(client, serverPath.c_str());
      
      // Send HTTP GET request
      int httpResponseCode = http.GET();
      
      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println(payload);
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

View raw code

Setting your network credentials

Modify the next lines with your network credentials: SSID and password. The code is well commented on where you should make the changes.

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Setting your serverName (API Key)

Modify the serverName variable to include your API key.

String serverName = "http://api.thingspeak.com/update?api_key=REPLACE_WITH_YOUR_API_KEY";

Now, upload the code to your board and it should work straight away. Read the next section, if you want to learn how to make the HTTP GET request.

HTTP GET Request

In the loop() is where you make the HTTP GET request every 10 seconds with random values:

String serverPath = serverName + "&field1=" + String(random(40));

// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());

// Send HTTP GET request
int httpResponseCode = http.GET();

The ESP32 makes a new request in the following URL to update the sensor field1 with a new value (30).

http://api.thingspeak.com/update?api_key=REPLACE_WITH_YOUR_API_KEY&field1=30

Then, the following lines of code save the HTTP response from the server.

if (httpResponseCode>0) {
  Serial.print("HTTP Response code: ");
  Serial.println(httpResponseCode);
  String payload = http.getString();
  Serial.println(payload);
}
else {
  Serial.print("Error code: ");
  Serial.println(httpResponseCode);
}

In the Arduino IDE serial monitor, you should see an HTTP response code of 200 (this means that the request has succeeded).

ESP32 ESP8266 NodeMCU HTTP POST Arduino IDE Serial Monitor Response

Your ThingSpeak Dashboard (under the Private View tab) should be receiving new readings every 10 seconds.

ESP32 ESP8266 NodeMCU HTTP GET and HTTP POST with Arduino IDE ThingSpeak Chart

For a final application, you might need to increase the timer or check the API call limits per hour/minute to avoid getting blocked/banned.

Wrapping Up

In this tutorial you’ve learned how to integrate your ESP32 with web services using HTTP GET requests. You can also make HTTP POST requests with the ESP32.

If you’re using an ESP8266 board, read:

You might also like reading:

I hope you liked this project. If you have any questions, post a comment below and we’ll try to get back to you.

If you like ESP32, you might consider enrolling in our course “Learn ESP32 with Arduino IDE“. You can also access our free ESP32 resources here.

Thank you for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch  With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course  Build IoT and home automation projects.

Arduino Step-by-Step Projects Âť Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

40 thoughts on “ESP32 HTTP GET with Arduino IDE (OpenWeatherMap.org and ThingSpeak)”

  1. Hello, this is my first time posting here.
    I want to know, can i use ArduinoJson library which made by bblanchon instead? is there any advantage of using the official one? also is there any difference in the code? i know that i ask a lot of question, but it will clear up a lot of my confusion. Thank You.

    Reply
  2. Hi,
    I’m using OpenWeather in sketch above explained and it seems that there are some mistakes. For example
    I dont’ know which meter are used for a temperature like 295.4 ? Also the coord of my location and country is quite different I receive JSON object of 9.36 long and 45.85 latid and I’ sure thatr it’s wrong as the right coordinates are 9°2′ 33″ 48 E and 45°50’49″92 N.
    The question is how can I modify and set correct values ?
    I think that will be a very nice sketch when correct.
    Regards Gianni

    Reply
    • Hi.
      The article refers the temperature units. The temperature comes in Kelvin Units.
      Double-check that you inserted the right location.
      That information is returned by the OpenWeatherMap API. Those are the coordinates it has saved for the specific location you’ve inserted.
      Regards,
      Sara

      Reply
      • You are indeed right about the temperature. If no units are entered, temperature is in Kelvin. You can add &units=metric to get Celsius or &units=imperial to get Fahrenheit

        The confusion about the latitued and longitude are that OpenWeatherMap uses degrees and decimal part of degrees, not degrees, minutes and seconds. Negative degrees are west of Greenwich

        Reply
      • Problem is when using this server path, it returns this error: “https” was not declared in this scope. I can’t get this server path to work!!

        Reply
    • // Convert JSONVar to String
      String tempStr = JSON.stringify(myObject[“main”][“temp”]);

      // Convert String to float
      float temperature = tempStr.toFloat();

      //float tempC = myObject["main"]["temp"].as<float>();
      Serial.print("Temperature: ");
      //Serial.println(tempC-273.0);
      Serial.println(temperature-276.15);

      Reply
  3. Thank you for the well documented ESP32 HTTP GET with Arduino IDE guid
    Having it up and running following question arised:
    How access values in a c++ comptational format e.g.

    Serial.println(myObject[“main”][“temp”]); prints – 275.16

    to convert this to an °C value I’ve to add 273.16.
    My question is how access and convert this or any other “JSON element” into a c++ variable. The openweathermap response embodies int, float, char, time_t etc values.
    Maybe you can give some examples
    Thank you for the great tutorial
    Joschen

    Reply
  4. I’ve had a lot of fun using your courses and tutorials. The OpenWeather included. Where can I find the instructions for getting all the information from the JSON object (cloud cover, etc.)? Thanks

    Reply
    • Hi.
      The Json object myObject contains all the information.
      You just need to access the key:value pairs you want.
      For example, for clouds:
      myObject[“clouds”][“all”]);
      I hope this helps.
      Regards,
      Sara

      Reply
  5. Hi,

    Thanks for the great tutorial! Unfortunately, I have got a problem:
    error: ‘httpGETRequest’ was not declared in this scope
    jsonBuffer = httpGETRequest(serverPath.c_str());

    I thought that might be something with the libraries, but they seems to be ok.

    BR,
    Pawel

    Reply
  6. Hi Sara,
    thanks for graet project tutorial!
    Can you help me please to convert the temperature data from Kelvin to Celsius?
    Serial.println(myObject[“main”][“temp”]); prints – 273.15
    doesn`t work in arduino sketch.

    And how to make the conversion of the unix-timestamps to an readable date-time format like: dd.mm.yyyy, hh:mm:ss ?

    Thanks in advanced!
    Rgds Matthias

    Reply
  7. Thanks for this. It has been helpful with my project.

    I recommend adding if(httpResponseCode==200) to the in the httpGETRequest function to validate that the HTTP status code from the server is OK.

    As written, your function will handle negative codes, which the http client will return if it encounters a client side error (for example a timeout).

    However, if the http client successfully communicated with the server, it will use the HTTP status code from the server, which could indicate an error.

    200 is the standard HTTP status code that means that the request has succeeded. If successful, the result should always be 200. Anything else is not normal, so I’m not going to try to process the returned data.

    HTTP status codes are always between 100-599.

    Common error status codes: 400=Bad request, 401=Authorization required, 403=Forbidden, 404=Not found, 500=Internal server error

    See this link for a list of HTTP status codes: developer.mozilla.org/en-US/docs/Web/HTTP/Status

    Reply
  8. Hi i did everthing what you did but it show me the failure for HTTPclient

    HTTPClient http;

    “HTTPClient was not declared in this scope”

    Reply
  9. Hi Sara,
    thanks for great project tutorial!
    Can you help me please to print the sunrise in format hh:mm:ss
    int sunrise = root[“sys”][“sunrise”]
    Thanks in advance Eddy

    Reply
  10. If you want to schwitch units to metric just replace this line:
    String serverPath = “http://api.openweathermap.org/data/2.5/weather?q=” + city + “,” + countryCode + “&units=metric&APPID=” + openWeatherMapApiKey;
    And if you want imperial units use this:
    String serverPath = “http://api.openweathermap.org/data/2.5/weather?q=” + city + “,” + countryCode + “&units=imperial&APPID=” + openWeatherMapApiKey;

    Reply
  11. Hi, Super great tutorial, very easy to follow.
    How can I get the values inside the “weather” ?

    “weather” is formatted a little different than the others.
    most of them are like this:
    “main”:{“temp”:21.53}

    but weather is like this:
    “weather”:[{“id”:500,”main}]

    whenever I try this: Serial.println(myObject[“weather”][“id”]);
    the output is “null”

    what’s the trick?

    Reply
  12. Hi great tutorial! Using the Openweather onecall and your example, i am trying to get the daily, 0, temp, max. How would my myObject look to get this value? It is formatted differently.
    this is an example of the response:
    {
    “lat”: xx.xxxxx,
    “lon”: -xx.xxxxx,
    “timezone”: “America/Chicago”,
    “timezone_offset”: -18000,
    “daily”: [{
    “dt”: 1631379600,
    “sunrise”: 1631360577,
    “sunset”: 1631405792,
    “moonrise”: 1631378640,
    “moonset”: 1631416740,
    “moon_phase”: 0.17,
    “temp”: {
    “day”: 84.27,
    “min”: 62.51,
    “max”: 89.98,
    “night”: 72.54,
    “eve”: 86.81,
    “morn”: 62.53
    },
    “feels_like”: {
    “day”: 83.41,
    “night”: 71.98,
    “eve”: 86.18,
    “morn”: 61.92
    },
    “pressure”: 1020,
    “humidity”: 39,
    “dew_point”: 56.82,
    “wind_speed”: 11.25,
    “wind_deg”: 218,
    “wind_gust”: 26.11,
    “weather”: [{
    “id”: 800,
    “main”: “Clear”,
    “description”: “clear sky”,
    “icon”: “01d”
    }],
    “clouds”: 0,
    “pop”: 0,
    “uvi”: 7.85
    }, {
    “dt”: 1631466000,
    “sunrise”: 1631447022,
    “sunset”: 1631492104,
    “moonrise”: 1631469360,
    “moonset”: 1631505720,
    “moon_phase”: 0.21,
    “temp”: {
    “day”: 87.19,
    “min”: 64.89,
    “max”: 93.6,
    “night”: 75.13,
    “eve”: 89.53,
    “morn”: 65.12
    },
    “feels_like”: {
    “day”: 86.18,
    “night”: 75.25,
    “eve”: 88.05,
    “morn”: 64.58
    },
    “pressure”: 1021,
    “humidity”: 37,
    “dew_point”: 58.32,
    “wind_speed”: 10.18,
    “wind_deg”: 208,
    “wind_gust”: 25.61,
    “weather”: [{
    “id”: 800,
    “main”: “Clear”,
    “description”: “clear sky”,
    “icon”: “01d”
    }],
    “clouds”: 0,
    “pop”: 0,
    “uvi”: 7.73
    }, {
    “dt”: 1631552400,
    “sunrise”: 1631533467,
    “sunset”: 1631578415,
    “moonrise”: 1631559960,
    “moonset”: 1631595120,
    “moon_phase”: 0.25,
    “temp”: {
    “day”: 87.71,
    “min”: 68.09,
    “max”: 89.44,
    “night”: 72.03,
    “eve”: 84.78,
    “morn”: 68.43
    },
    “feels_like”: {
    “day”: 89.89,
    “night”: 72.84,
    “eve”: 86.14,
    “morn”: 69.06
    },
    “pressure”: 1020,
    “humidity”: 48,
    “dew_point”: 65.71,
    “wind_speed”: 15.12,
    “wind_deg”: 194,
    “wind_gust”: 23.13,
    “weather”: [{
    “id”: 803,
    “main”: “Clouds”,
    “description”: “broken clouds”,
    “icon”: “04d”
    }],
    “clouds”: 78,
    “pop”: 0,
    “uvi”: 7.47
    }, {
    “dt”: 1631638800,
    “sunrise”: 1631619912,
    “sunset”: 1631664726,
    “moonrise”: 1631650320,
    “moonset”: 0,
    “moon_phase”: 0.28,
    “temp”: {
    “day”: 76.28,
    “min”: 65.19,
    “max”: 77.77,
    “night”: 67.57,
    “eve”: 71.92,
    “morn”: 65.53
    },
    “feels_like”: {
    “day”: 77,
    “night”: 68.49,
    “eve”: 72.91,
    “morn”: 66.31
    },
    “pressure”: 1017,
    “humidity”: 72,
    “dew_point”: 66.52,
    “wind_speed”: 11.9,
    “wind_deg”: 172,
    “wind_gust”: 22.73,
    “weather”: [{
    “id”: 500,
    “main”: “Rain”,
    “description”: “light rain”,
    “icon”: “10d”
    }],
    “clouds”: 98,
    “pop”: 0.59,
    “rain”: 1.17,
    “uvi”: 7.71
    }, {
    “dt”: 1631725200,
    “sunrise”: 1631706356,
    “sunset”: 1631751037,
    “moonrise”: 1631740260,
    “moonset”: 1631685000,
    “moon_phase”: 0.32,
    “temp”: {
    “day”: 80.24,
    “min”: 67.57,
    “max”: 83.62,
    “night”: 73.54,
    “eve”: 77.18,
    “morn”: 67.68
    },
    “feels_like”: {
    “day”: 82.96,
    “night”: 74.55,
    “eve”: 78.12,
    “morn”: 68.61
    },
    “pressure”: 1015,
    “humidity”: 67,
    “dew_point”: 68.45,
    “wind_speed”: 8.97,
    “wind_deg”: 159,
    “wind_gust”: 16.64,
    “weather”: [{
    “id”: 500,
    “main”: “Rain”,
    “description”: “light rain”,
    “icon”: “10d”
    }],
    “clouds”: 87,
    “pop”: 0.94,
    “rain”: 3.38,
    “uvi”: 8
    }, {
    “dt”: 1631811600,
    “sunrise”: 1631792801,
    “sunset”: 1631837348,
    “moonrise”: 1631829720,
    “moonset”: 1631775240,
    “moon_phase”: 0.35,
    “temp”: {
    “day”: 87.21,
    “min”: 67.42,
    “max”: 87.21,
    “night”: 75.33,
    “eve”: 76.77,
    “morn”: 67.42
    },
    “feels_like”: {
    “day”: 88.79,
    “night”: 76.28,
    “eve”: 77.67,
    “morn”: 68.38
    },
    “pressure”: 1015,
    “humidity”: 47,
    “dew_point”: 64.98,
    “wind_speed”: 9.73,
    “wind_deg”: 146,
    “wind_gust”: 14.41,
    “weather”: [{
    “id”: 500,
    “main”: “Rain”,
    “description”: “light rain”,
    “icon”: “10d”
    }],
    “clouds”: 66,
    “pop”: 0.31,
    “rain”: 0.13,
    “uvi”: 8
    }, {
    “dt”: 1631898000,
    “sunrise”: 1631879246,
    “sunset”: 1631923659,
    “moonrise”: 1631918640,
    “moonset”: 1631865660,
    “moon_phase”: 0.39,
    “temp”: {
    “day”: 77.13,
    “min”: 69.46,
    “max”: 77.13,
    “night”: 69.46,
    “eve”: 71.4,
    “morn”: 70.79
    },
    “feels_like”: {
    “day”: 78.06,
    “night”: 70.57,
    “eve”: 72.37,
    “morn”: 71.8
    },
    “pressure”: 1017,
    “humidity”: 75,
    “dew_point”: 68.74,
    “wind_speed”: 12.75,
    “wind_deg”: 164,
    “wind_gust”: 23.62,
    “weather”: [{
    “id”: 500,
    “main”: “Rain”,
    “description”: “light rain”,
    “icon”: “10d”
    }],
    “clouds”: 100,
    “pop”: 0.99,
    “rain”: 7.3,
    “uvi”: 8
    }, {
    “dt”: 1631984400,
    “sunrise”: 1631965691,
    “sunset”: 1632009969,
    “moonrise”: 1632007200,
    “moonset”: 1631956080,
    “moon_phase”: 0.42,
    “temp”: {
    “day”: 81.43,
    “min”: 68.77,
    “max”: 81.5,
    “night”: 72.5,
    “eve”: 75.52,
    “morn”: 68.77
    },
    “feels_like”: {
    “day”: 85.19,
    “night”: 73.81,
    “eve”: 76.91,
    “morn”: 69.87
    },
    “pressure”: 1015,
    “humidity”: 69,
    “dew_point”: 70.27,
    “wind_speed”: 9.53,
    “wind_deg”: 162,
    “wind_gust”: 16.84,
    “weather”: [{
    “id”: 500,
    “main”: “Rain”,
    “description”: “light rain”,
    “icon”: “10d”
    }],
    “clouds”: 90,
    “pop”: 1,
    “rain”: 7.29,
    “uvi”: 8
    }]
    }

    Reply
  13. Maybe a silly question, I am writing some software where the AsyncTCP.h and ESPAsyncWebServer.h are alreay included. Do I still need to include HTTPClient.h to get the Json data from the API?

    Kind regards,
    Michiel

    Reply
  14. Hi,
    I’m trying to figure out how to create a web page from the data from Openweather.
    The pages I have done in the past are from sensor data taken directly from an Uno and ethernet shield, but i’m stumped with this.
    Any help would be great.
    Ta

    Reply
  15. Hi
    i found that:

    HTTP Response code: 400

    400 Bad Request

    Bad Request

    Your browser sent a request that this server could not understand.
    Reason: You’re speaking plain HTTP to an SSL-enabled server port.
    Instead use the HTTPS scheme to access this URL, please.

    How we can call api with https?

    Reply
  16. I would like to see the degrees in Celcius as well as the clouds in the serial monitor between the temperature and the pressure, I cannot find how to do this. Please help me. Thanks in advance

    Reply
    • Hi
      For the temperature in Celsius you need to add the calculation on the code to manually do that.
      temperature (Celsius) = Temperature (kelvin) – 276.15

      To get the clouds:
      Serial.println(myObject[“weather”][“main”]);
      If that doesn’t work, try:
      Serial.println(myObject[“weather”][][“main”]);
      I hope this helps.
      Regards,
      Sara

      Reply
      • Serial.println(myObject[“weather”][0][“description”]); //OK!

        Serial.println(myObject[“weather”][][“main”]); // No !!!!!

        Reply
        • First post 😉
          I integrated e-ink display with GxEPD2 to the weather forecast and would like to display more infos also first :
          Thanks, you answered the question I was about to ask !

          Then I ask the next one, I ask him this :

          Serial.println(myObject[“weather”][0][“description”]);

          and I get :
          ´´´
          “fog”
          ´´´
          how get : fog without the “” signs ?
          It’s only cosmetic and I will survive without 😉 with python it is simple but here I’m lost.
          If I find my answer I’ll post it here. I would try to avoid to make a loop to eliminate first and last character. Is there any equivalent to the python [1:][:-1] or line.split or so ?
          I’ll try to convert string to slice of chars for now or focus on other aspects of the project.

          37_6333k0

          Reply
        • Thanks for this – I am still puzzled though as to what the [0] does in terms of decoding. Is it referring to the first variable in an array? I have played around to try to acces things like sunrise and feels_like but haven’t been able to figure how how to write it.

          Reply
      • // Convert JSONVar to String
        String tempStr = JSON.stringify(myObject[“main”][“temp”]);

        // Convert String to float
        float temperature = tempStr.toFloat();

        //float tempC = myObject["main"]["temp"].as<float>();
        Serial.print("Temperature: ");
        //Serial.println(tempC-273.0);
        Serial.println(temperature-276.15);

        Reply
  17. For those getting a httpGETRequest prolem and using VSCODE, you have to put that function before the loop(). It is a function order thing handled differrently by some IDEs.

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.