How to Display the Number of API Calls a Customer Made vs Plan Limits in your SaaS app

Updated:
3 minute read

We at Moesif try to supply our customers with state of the art monitoring and analytics to get the most out of their APIs. One of these tools is our Management API.

The Moesif Management API allows our customers to retrieve the data we stored about their APIs. With this API they can check things like, how many requests happened or who did the most requests.

One of the most pressing questions we get asked a lot by our B2B customers:

“How many API calls have been made by one user in the last 30 days?”

In this article, we will learn how to use the management API to answer that question.

What

We will use cURL and Node.js. Also, the management API isn’t available for Moesif customers on a free plan, so a paid subscription is necessary.

The management API doesn’t support CORS, so using it directly from a browser won’t be possible.

Get a Token for the Management API

First, we need to retrieve a management API token. This key has to be sent via the Authorization header alongside every request.

For this, we need to go to the management API page on the Moesif site.

Moesif Menu

On that page, we have to select a scope and click on Generate Token.

In our case of the API calls, we only need to select the read:events scope.

Use the Token with cURL

The simplest way to test if everything worked, is, to copy the example that showed up below our token after we clicked Generate Token.

curl -X GET https://api.moesif.com/v1 \
  -H 'Accept: application/json' \
  -H 'Authorization:Bearer <API_TOKEN>'

This request will show something like that:

{ "name": "Moesif Management API", "region": "eastus" }

Now, let us modify the cURL request so it responds with our desired answer: How many API calls have been made by one user in the last 30 days?

curl -X POST 'https://api.moesif.com/search/~/count/events?from=-720h&to=now' \
  -H 'Content-Type: application/json' \
  -H 'Authorization:Bearer <API_TOKEN>' \
  -d '{"post_filter":{"bool":{"should":{"term":{"user_id.raw":"<USER_ID>"}}}}}'

What is happening here?

We are sending a POST request to the /search/~/count/events endpoint of the Management API and use the query parameters from and to to specify the period we want to include in the results. 720h divided by 24h gives us the 30 days we want.

We need to set the right Content-Type and include our API_TOKEN in the Authorization header.

Also, we need to send a JSON object as query. This is the case because the Management API uses the Elasticsearch SDL to perform search and filter.

The query we defined gets us only the calls of the user with that specific ID.

The response looks like that:

{
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "hits": [],
    "total": 5,
    "max_score": 0
  },
  "took": 1,
  "timed_out": false
}

We can see that our search had a total amount of hits which resembles our total API calls.

Use the Token with Node.js

To set up a simple server that will act as a proxy between our client and the management API, we can use Node.js.

const http = require("http");
const https = require("https");

const API_TOKEN = "<API_TOKEN>";
const USER_ID = "<USER_ID>";

const quotaOneMillionCalls = 1000000;

const handleRequest = (request, response) => {
  const requestOptions = {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_TOKEN}`,
      "Content-Type": "application/json"
    }
  };

  const query = JSON.stringify({
    post_filter: {
      bool: {
        should: {
          term: { "user_id.raw": USER_ID }
        }
      }
    }
  });

  https
    .request(
      "https://api.moesif.com/search/~/count/events?from=-720h&to=now",
      requestOptions,
      moesifResponse => {
        let data = "";
        moesifResponse
          .on("data", chunk => (data += chunk))
          .on("end", () => {
            const apiCalls = JSON.parse(data).hits.total;
            const usage = apiCalls / (quotaOneMillionCalls / 100);
            response.end(
              `User ${USER_ID} made ${apiCalls} API calls. That is ${usage}% of their quota.`
            );
          });
      }
    )
    .end(query);
};

http.createServer(handleRequest).listen(8888);

In this example, we use Node.js’ http module to start an HTTP server and its https module to make a request to the management API.

Our HTTP server responds to all requests it receives with a text describing how many request have happened in the last 30 days.

Conclusion

With its Management API Moesif provides a strong tool to get the important metrics out of your API.

The Elasticsearch DSL makes it very flexible and since it is just another HTTP API, it can be quickly integrated with whatever analytics tool you desire.

Do you spend a lot of time debugging customer issues?
Moesif makes debugging easier for RESTful APIs and integrated apps


Learn More

Leave a comment