Gangmates
  • Getting Started
  • GENERAL USER GUIDES
    • Directory Services
      • Users
        • Quick Guide for Completing the CSV Template
          • Quick Guide: Formatting the Account Number Column as Text
        • New User Account Activation
      • User Types
      • Third Party Providers
    • Company Services
    • Security
      • Roles
      • Security Settings
    • Configurations
      • Branding
        • Logo
        • Domains
        • Add Email Address Format
          • Custom Expressions for Email Address Format
      • Company Settings
      • Bank Names and Codes Reference
      • Categories and Subcategories
    • Finance
      • Invoice
      • Payroll
        • Create Payslip
          • Understanding Payslip Calculations
        • Payroll Settings
        • Custom Contributions
      • Payment Processing
    • Performance
    • Organization Structure
  • API Documentation
    • API Overview
      • 🔌Authentication
      • ⏱️Rate Limits
    • API Reference
      • Company Management
      • Users Management
      • Payroll Management
        • Payroll Settings
      • Payment Processing
      • Domain Management
      • Wallet Top-Up
      • Invoices Management
  • Legal
    • Compliance and Regulatory Documents
      • Service Agreement
      • Service Level Agreement (SLA)
      • Privacy Policy
      • Data Processing Agreement (DPA)
      • Non-Disclosure Agreement (NDA)
      • Payroll Processing Agreement
      • Master Services Agreement (MSA)
      • Onboarding Checklist
      • Refund Policy
      • Terms and Conditions
Powered by GitBook
On this page
  • Handling Rate Limits
  • Examples
  1. API Documentation
  2. API Overview

Rate Limits

Our API employs rate limiting to ensure fair usage and to prevent abuse. Here are the details:

  • Rate Limit: 100 requests per minute.

  • Response Code for Exceeding Limit: 429 Too Many Requests

  • Retry-After Header: The response will include a Retry-After header indicating the number of seconds to wait before making further requests.

Handling Rate Limits

When your application exceeds the rate limit, it will receive a 429 Too Many Requests response. Here's how to handle this:

  1. Check for the 429 Status Code: When you receive a response, check if the status code is 429.

  2. Read the Retry-After Header: This header will tell you how many seconds to wait before retrying the request.

  3. Implement Retry Logic: Wait for the specified time and then retry the request.

Examples

Here are examples of how you can implement this logic in different programming languages:


const axios = require('axios');

async function makeApiRequest(url, options) {
    try {
        const response = await axios(url, options);
        return response.data;
    } catch (error) {
        if (error.response && error.response.status === 429) {
            // Extract the Retry-After header value
            const retryAfter = parseInt(error.response.headers['retry-after'], 10);

            if (!isNaN(retryAfter)) {
                console.log(`Rate limit exceeded. Retrying after ${retryAfter} seconds...`);
                await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
                return makeApiRequest(url, options); // Retry the request
            } else {
                console.error('Rate limit exceeded but no Retry-After header found.');
            }
        } else {
            console.error('Request failed:', error.message);
        }
    }
}

// Example usage
const url = 'https://api.example.com/your-endpoint';
const options = {
    method: 'GET',
    headers: {
        'Authorization': 'Bearer your_token_here'
    }
};

makeApiRequest(url, options)
    .then(data => {
        console.log('API Response:', data);
    })
    .catch(error => {
        console.error('Request failed:', error.message);
    });
            


import time
import requests

def make_api_request(url, headers):
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as err:
        if err.response.status_code == 429:
            retry_after = int(err.response.headers.get('Retry-After', 0))
            if retry_after > 0:
                print(f'Rate limit exceeded. Retrying after {retry_after} seconds...')
                time.sleep(retry_after)
                return make_api_request(url, headers)
            else:
                print('Rate limit exceeded but no Retry-After header found.')
        else:
            print(f'Request failed: {err}')

# Example usage
url = 'https://api.example.com/your-endpoint'
headers = {
    'Authorization': 'Bearer your_token_here'
}

response_data = make_api_request(url, headers)
if response_data:
    print('API Response:', response_data)
            


import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class ApiClient {
    private static final HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    public static String makeApiRequest(String url, String token) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI(url))
                .header("Authorization", "Bearer " + token)
                .GET()
                .build();

        HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() == 429) {
            String retryAfterHeader = response.headers().firstValue("Retry-After").orElse("0");
            int retryAfter = Integer.parseInt(retryAfterHeader);

            if (retryAfter > 0) {
                System.out.println("Rate limit exceeded. Retrying after " + retryAfter + " seconds...");
                Thread.sleep(retryAfter * 1000);
                return makeApiRequest(url, token);
            } else {
                System.out.println("Rate limit exceeded but no Retry-After header found.");
            }
        }

        return response.body();
    }

    public static void main(String[] args) {
        String url = "https://api.example.com/your-endpoint";
        String token = "your_token_here";

        try {
            String response = makeApiRequest(url, token);
            System.out.println("API Response: " + response);
        } catch (Exception e) {
            System.err.println("Request failed: " + e.getMessage());
        }
    }
}
            

PreviousAuthenticationNextAPI Reference

Last updated 9 months ago

By implementing the above retry mechanism, your application can handle rate limiting gracefully, ensuring that your requests are processed once the rate limit resets. If you have any questions or need further assistance, please contact our support team at .

⏱️
support@gangmates.com