Search code examples
jqueryajaxhttp-status-codes

How do i get HTTP status code 200 instead of 202 from an ajax call


The below code always receives a HTTP '202 Accepted' status code: enter image description here

When I try the same API using postman I get 200 OK": enter image description here

function ExportStatus() {
  function ExportStatusAjax() {
    $.ajax({
      type: "GET",
      url: "https://api.powerbi.com/v1.0/myorg/groups/" + groupId + "/reports/" + reportId + "/exports/" + exportId + "",
      headers: {
        "Authorization": "Bearer " + accessToken
      },
      success: function(data, textStatus, jqXHR) {
        if (jqXHR.status == 200) {
          GetExportFile()
        } else {
          ExportStatusAjax()
        }
      },
      error: function(err) {
        alert(error)
      }
    });
  }

  ExportStatusAjax()
}

Solution

  • I am not familiar with Power BI, so I can't say for sure, but judging by your code and the API status codes, this looks like a case of an asynchronous API. What that means is, instead of the traditional model in HTTP where the client submits a request and gets the response back (this is a 200, a.k.a. OK), a client submits an HTTP request and the response is a placeholder to tell you that the real response is not ready yet.

    202 is called Accepted and I believe that in this situation it is being used to indicate your request has been accepted into a queue. The idea being that, if you keep retrying, eventually it will be done and you'll get the real response, which comes with a status code of 200. Reports, analytics, or other sorts of computationally expensive workloads often follow this pattern.

    This approach is a common pattern. If that is in fact what is happening here, then your code is probably correct and seeing the response flip between 202 and 200 is normal.

    With that said, your approach is constantly hammering the server. As soon as it gets back a 202, it immediately retries, which adds load to the remote system, which theoretically may actually slow it down.

    I suggest putting in a timer to delay the retries, maybe every 3 seconds or 5 seconds or so. The setTimeout function can help you.