How do I solve/handle an occasional API 400 error

user1965406

I have a simple script that makes calls to 8 different APIs every 30 minutes. Just one of these APIs returns a 400 bad request error about once every couple of days, which seems a little odd. Can anyone suggest what I might be doing wrong, or perhaps a simple way to retry the call on failure if it's not my fault?

var hayurl = "https://api.naturalresources.wales/riverlevels/v1/all?Location=4016";

var hayheaders = {
  "contentType": "application/json",
  "headers": {"Ocp-Apim-Subscription-Key": "xxxxxxxxxxxx"}
};

var hayresponse = UrlFetchApp.fetch(hayurl, hayheaders);

Most of the time it simply returns the data I want but the occasional fails have me stumped!

Diego

If you know what the correct response code is, then mute HTTP exceptions and check for it using HTTPResponse.getResponseCode(). In the example below, I assume the correct response code is 200.

function getApiData() {
  var url = "https://api.naturalresources.wales/riverlevels/v1/all?Location=4016";
  var params = {
    "contentType": "application/json",
    "headers": {"Ocp-Apim-Subscription-Key": "xxxxxxxxxxxx"},
    "muteHttpExceptions": true // Without this, you'll still get an error
  };
  var maximumAttempts = 5; // Set a limit of retry attempts to prevent an infinite loop
  var attemptCount = 0;
  do { // Execute this block
    attemptCount++; // This needs to be BEFORE the request in case of failure, otherwise it will never increment
    var response = UrlFetchApp.fetch(url, params);
  } while (response.getResponseCode() != 200 && attemptCount < maximumAttempts); // If not 200, execute the block again
  return response;
}

Alternatively, use a try...catch statement. If you use this method, you neither need to mute HTTP exceptions nor know the exact successful response code. By disabling muteHttpExceptions (it is disabled by default), the UrlFetchApp.fetch() call will throw the error that you have been seeing. We're counting on this happening, because the error will be caught and then trigger the retry attempt. This may be a preferable strategy because it would catch other errors, whereas my first approach only catches the very specific instance where the response code is not exactly 200.

function getApiData() {
  var url = "https://api.naturalresources.wales/riverlevels/v1/all?Location=4016";
  var params = {
    "contentType": "application/json",
    "headers": {"Ocp-Apim-Subscription-Key": "xxxxxxxxxxxx"}
  };
  var maximumAttempts = 5; // Set a limit of retry attempts to prevent an infinite loop
  var attemptCount = 0;
  do { // Execute this block
    var isErrored = false; // Reset to false at the start of each new iteration
    try {
      attemptCount++; // This needs to be BEFORE the request in case of failure, otherwise it will never increment
      var response = UrlFetchApp.fetch(url, params);
    } catch (err) {
      isErrored = true; // If there was an error, set to true so the script will try again
    }
  } while (isErrored && attemptCount < maximumAttempts); // If isErrored, execute the block again
  return response;
}

Just in case your not familiar the looping logic, I'm using a do...while statement, which will execute a block of code first and then check a condition to see if that code should continue to be executed.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I avoid AWS API Gateway returning a 400 error?

Why do I get a 400 Bad Request error from api

How do I fix a HTTP Error 400: Bad Request?

I'm seeing occasional build failure due to auto generated files (automake). How do I create dependencies between autogenerated files?

Why do I get Error 400 Bad Request "INVALID_X_API_USER_HEADER" while trying to call the AdobeSign API?

How do I print with jt400?

How do I access AS/400 using SQLAlchemy?

How do I get checkbox "on" using Python Flask without causing a 400 bad request error?

How do I fix the "Error during WebSocket handshake: Unexpected response code: 400"?

How could my mutation from apollo client get 400 error, while I can do that from playground?

How do I fix a 400 Bad Request error in .Net Core POST operation?

How do I fix error 400 on apt-get dist-upgrade

Why do I keep getting a 400 Bad Request Error when exchanging code for access token from Spotify API?

can't do POST to api, error 400 using fetch

Error 400 with Openweathermap API

How to fix occasional EINVAL error when calling pthread_create

Occasional gnutls handshake error

How do I handle if the api error message is undefined?

How do I catch an API response error with observables?

How do I query an API latency Error Budget from Prometheus

Rails API how do I send the active record validation error?

How do I fix 401 error when using OMDB API?

How do I solve page not found error in flask rest api

How do I render API error responses in reactJS + axios + nodeJS?

How to fix imgur api error status 400, 417 errors

How to do a PUT request with jQuery / Axios? It always returns error 400

How do I make 400k requests 200 at a time?

Occasional error while deleting files

Why I get a "Bad Request" Error 400 when I try to connect with Api with fetch?