apiresthttpesp8266arduino-esp8266

How to make an API Call every second using ESP8266?


I tried making a HTTP request to my localhost that is running Laravel Api.

if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin(url + "update");      //request destination
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");  //content-type header

    String stringData = "payload=" + data;
    int httpCode = http.POST(stringData);
    String payload = http.getString();
    Serial.print(httpCode);
    http.end();
  }
 delay(2000);
}

When I reduce delay value <= 2000, nodeMCU is not performing as expected. While testing getting 429 error.

Please suggest an alternative that can update every second.


Solution

  • 429 Too Many Requests "indicates the user has sent too many requests in a given amount of time". The server could be slow, or rate limited.

    The server may send a Retry-After header; if it does, it tells you how long you have to wait before a new request is made.

    I suspect you would have to change things on the server side to make it as fast as you want; I doubt the ESP8266 is to blame.

    Note that if handling a request takes longer than 1s, you're out of luck anyway.

    BTW could you try the code below and see if it works? Just to rule out some other potential problems. It removes the inefficient delay() and only does HTTPClient http; once.

    HTTPClient http;
    unsigned long int lastPost = 0;
    int postInterval = 1000; // Post every second
    
    void setup() {
      // Setup stuffs
    }
    
    void loop() {
      if (WiFi.status() == WL_CONNECTED && (millis() - lastPost) >= postInterval) {
        http.begin(url + "update"); //request destination
        http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //content-type header
        String stringData = "payload=" + data;
        int httpCode = http.POST(stringData);
        String payload = http.getString();
        Serial.print(httpCode);
        http.end();
    
        lastPost = millis();
      }
    }
    

    Untested, just typed it in, but you get the idea.