Error 400 in weatherapi

I am trying to get a JSON response from WeatherApi, and it's giving me error 400, other websites work and show 200 but WeatherApi shows code 400.

Here's the code:

#include <ESP8266WiFi.h>

const char* ssid = "************";
const char* password = "************";
const int httpPort = 80;

const char* host = "api.weatherapi.com";

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

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Print the IP address
  Serial.println(WiFi.localIP());

  Serial.println("type enter in the Serial monitor to trigger a request");

}

void loop() {
  if (Serial.read() == '\n') { // type enter in the Serial monitor to trigger a request
    WiFiClient client;
    if (!client.connect(host, httpPort)) {
      Serial.print("connection to "); Serial.print(host); Serial.println(" failed.");
      return;
    }

    String url = "/v1/current.json?key=**************&q=Castellon de la Plana&aqi=no";
    Serial.print("Requesting URL: ");  Serial.print("http://"); Serial.print(host); Serial.println(url);

    client.print("GET ");
    client.print(url);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(host);
    client.println("Connection: close\r\n");

    while (!client.available()) yield(); // active wait for the answer (bad)

    Serial.println("Response:\n----------------------------");
    while (client.available())  Serial.write(client.read()); // dump the answer to the Serial monitor
    Serial.println();
    Serial.println("\n----------------------------");
    Serial.println("closing connection");
    client.stop();
    Serial.println("type enter in the Serial monitor to trigger a request");

For the code to work, you have to put your Wi-Fi credentials and your API key

Someone else reported the same problem today. Maybe find that post and see what responses they got. I suspect an issue with the API.

Your URL has spaces in it. Normally replaced with %20

"/v1/current.json?key=**************&q=Castellon de la Plana&aqi=no"

don't use the WifiClient for HTTP GET requests on an ESP8266. Use the HTTPClient and check the examples in the IDE how to use it.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.