API Testing : Check rate limiting

Verify that the API correctly handles rate limiting and returns the correct HTTP status code.

Language: Java

Framework: Rest assured

copy
1/​/​Assuming Base URI: http:/​/​api.example.com2/​/​Assuming rate limit threshold: 100 requests/​hour3/​/​Assuming API endpoint for rate limiting: http:/​/​api.example.com/​ratelimit45import static io.restassured.RestAssured.*;6import org.testng.annotations.Test;78public class RateLimitTest {9 10@Test11public void verifyRateLimit(){12 given().when().get("http:/​/​api.example.com/​ratelimit").then().statusCode(200);13 /​/​Assuming response body contains rate limit information, parse it and check against the threshold14 int rateLimit = Integer.parseInt(get("http:/​/​api.example.com/​ratelimit").body().jsonPath().getString("threshold"));15 if(rateLimit >= 100){16 /​/​Assuming rate limit is correctly enforced, send 101st request and check status code17 given().when().get("http:/​/​api.example.com").then().statusCode(429);18 }19}2021/​/​Code to connect to remote client with desired capabilities22/​*23public void connectToRemoteClient(){24 DesiredCapabilities capabilities = new DesiredCapabilities();25 capabilities.setBrowserName("Chrome");26 capabilities.setPlatform(Platform.LINUX);27 WebDriver driver = new RemoteWebDriver(new URL("http:/​/​localhost:4444/​wd/​hub"), capabilities);28 driver.get("http:/​/​api.example.com");29} 30*/​3132}

Language: Java

Framework: Rest assured

copy
1/​/​Assumptions: 2/​/​1. API endpoint: https:/​/​api.example.com 3/​/​2. Rate limiting is set at 100 requests per minute 4/​/​3. HTTP status code 429 will be returned if rate limit is exceeded56import static io.restassured.RestAssured.*;7import static org.hamcrest.Matchers.*;89public class RateLimitTest {1011 @Test12 public void testRateLimit(){13 14 /​/​Assuming rate limit is set at 100 requests per minute15 int requestCount=0;16 17 /​/​Sending 100 requests within a minute to ensure rate limit is not exceeded18 for(int i=0;i<100;i++){19 given().get("https:/​/​api.example.com")20 .then().statusCode(200);21 requestCount++;22 }23 24 /​/​Sending another request to exceed rate limit and verifying if HTTP status code 429 is returned25 given().get("https:/​/​api.example.com")26 .then().statusCode(429);27 }28 29 /​/​Connecting to remote client with desired capabilities30 WebDriver driver = new RemoteWebDriver(new URL("http:/​/​localhost:4444/​wd/​hub"), DesiredCapabilities.chrome());31}

Language: Java

Framework: Rest assured

copy
1import static io.restassured.RestAssured.*;2import static org.hamcrest.Matchers.*;34import org.junit.jupiter.api.BeforeAll;5import org.junit.jupiter.api.Test;67public class APITest {89 private static final String BASE_URL = "https:/​/​example-api.com";10 private static final String API_KEY = "your-api-key";1112 @BeforeAll13 static void setUp() {14 baseURI = BASE_URL;15 header("Api-Key", API_KEY);16 }1718 @Test19 void testRateLimiting() {20 String userAccount = "your-user-account";21 String ipAddress = "192.168.1.1";22 int requestsLimitPerHour = 1000;2324 given().pathParam("userAccount", userAccount)25 .pathParam("ipAddress", ipAddress)26 .when()27 .get("/​v1/​data/​{userAccount}/​{ipAddress}")28 .then()29 .statusCode(anyOf(is(429), is(200)))30 .header("X-RateLimit-Limit", String.valueOf(requestsLimitPerHour))31 .header("X-RateLimit-Remaining", notNullValue());32 }33}3435/​/​ Remote client with desired capabilities can be connected with commented code below3637/​/​ import org.openqa.selenium.remote.DesiredCapabilities;38/​/​ import org.openqa.selenium.remote.RemoteWebDriver;39/​/​ import java.net.URL;40/​/​41/​/​ DesiredCapabilities capabilities = new DesiredCapabilities();42/​/​ capabilities.setBrowserName("chrome");43/​/​ capabilities.setVersion("latest");44/​/​ capabilities.setCapability("enableVNC", true);45/​/​46/​/​ URL remoteUrl = new URL("http:/​/​localhost:4444/​wd/​hub");47/​/​ RemoteWebDriver driver = new RemoteWebDriver(remoteUrl, capabilities);

Language: Javascript

copy
1/​/​ Mocha + Chai23/​/​Assuming the API endpoint - "https:/​/​api.example.com/​rate-limit"4/​/​Assuming the rate limit for the API - "10 requests per minute"56const request = require('request');7const chai = require('chai');8const expect = chai.expect;910describe('Rate Limiting API Test', () => {11 it('Should return 429 response when rate limit is exceeded', (done) => {12 /​/​Send 10 requests in less than a minute to exceed rate limit13 for(let i = 0; i < 10; i++) {14 request('https:/​/​api.example.com/​rate-limit', (err, res) => {15 if (err) { return done(err); }16 });17 }1819 /​/​Send an additional request to verify if the API returns 429 status code20 request('https:/​/​api.example.com/​rate-limit', (err, res) => {21 if (err) { return done(err); }22 expect(res.statusCode).to.equal(429);23 done();24 });25 });26});2728/​/​Code to connect to remote client with desired capabilities 29const webdriver = require("selenium-webdriver");30const { remote } = require("webdriverio");31const capabilities = {32 browserName: 'chrome',33 platformName: 'Android'34};35const options = {36 hostname: "localhost",37 port: 4444,38 path: "/​wd/​hub",39 capabilities: capabilities,40 logLevel: "error"41}42const client = await remote(options);43const driver = await new webdriver.Builder().forBrowser('chrome').build(); /​/​ local driver44/​/​Now use either 'client' or 'driver' object to perform automation testing.

Language: Javascript

copy
1/​/​ Mocha + Chai + SuperTest.23/​/​Assuming the rate limiting is set to 10 requests per minute4/​/​Assuming the API endpoint is http:/​/​example.com/​api56const request = require('supertest');7const app = require('../​app'); /​/​import the API code89describe('API Testing - Rate Limiting', () => {10 it('should allow 10 requests per minute and return 200 status code', (done) => {11 let count = 0;12 const interval = setInterval(() => {13 request(app)14 .get('/​api')15 .expect(200)16 .end((err, res) => {17 if (err) return done(err);18 count++;19 if (count === 10) {20 clearInterval(interval);21 done();22 }23 });24 }, 6000); /​/​60 seconds divided by 10 requests25 });2627 it('should reject requests after 10 requests and return 429 status code', (done) => {28 let count = 0;29 const interval = setInterval(() => {30 request(app)31 .get('/​api')32 .end((err, res) => {33 if (err) {34 if (res.statusCode === 429) {35 clearInterval(interval);36 done();37 } else {38 return done(err);39 }40 } else {41 count++;42 if (count === 11) {43 clearInterval(interval);44 return done(new Error('Expected request to be rejected'));45 }46 }47 });48 }, 6000); /​/​60 seconds divided by 10 requests49 });50});

Language: Javascript

copy
1/​/​ Mocha and Chai.23/​/​Assumptions:4/​/​1. The API endpoint for rate limiting is /​rate-limit/​check5/​/​2. The API returns a JSON response with key "remaining_requests" and value as the number of remaining requests for the user account or IP address.6/​/​3. The API returns a status code 429 if the rate limit has been exceeded.7/​/​4. The API requires user authentication to access the rate limiting endpoint.89const chai = require('chai');10const expect = chai.expect;11const request = require('supertest');1213describe('API Rate Limiting', function() {14 before(function() {15 /​/​Initialize server or API endpoint here.16 /​/​Example: startServer();17 });1819 after(function() {20 /​/​Close server or API endpoint here.21 /​/​Example: stopServer();22 });2324 it('should correctly handle rate limiting based on user account', function(done) {25 /​/​Assume rate limit of 10 requests per minute for user accounts.26 const authUser = {username: 'testuser', password: 'testpassword'};27 const num_requests = 10;28 const interval = 60; /​/​in seconds2930 /​/​Simulate user making 10 requests within 60 seconds.31 /​/​Assume /​rate-limit/​check endpoint returns JSON response.32 for(let i=0; i<num_requests; i++) {33 request34 .get('/​rate-limit/​check')35 .auth(authUser.username, authUser.password)36 .expect(200)37 .end(function(err, res) {38 if (err) return done(err);39 expect(res.body).to.have.property('remaining_requests', num_requests-i-1);40 if(i == num_requests-1) done();41 });42 /​/​Wait 6 seconds between requests.43 /​/​Assume setTimeout returns a Promise.44 await new Promise(resolve => setTimeout(resolve, interval/​num_requests*1000));45 }4647 /​/​Simulate user making 1 extra request after limit has been reached.48 request49 .get('/​rate-limit/​check')50 .auth(authUser.username, authUser.password)51 .expect(429, done);52 });5354 it('should correctly handle rate limiting based on IP address', function(done) {55 /​/​Assume rate limit of 100 requests per minute for IP addresses.56 const num_requests = 100;57 const interval = 60; /​/​in seconds5859 /​/​Simulate 100 requests from same IP address within 60 seconds.60 /​/​Assume /​rate-limit/​check endpoint returns JSON response.61 for(let i=0; i<num_requests; i++) {62 request63 .get('/​rate-limit/​check')64 .set('X-Forwarded-For', '192.168.1.1') /​/​Assume IP address of client is 192.168.1.165 .expect(200)66 .end(function(err, res) {67 if (err) return done(err);68 expect(res.body).to.have.property('remaining_requests', num_requests-i-1);69 if(i == num_requests-1) done();70 });71 /​/​Wait 0.6 seconds between requests.72 /​/​Assume setTimeout returns a Promise.73 await new Promise(resolve => setTimeout(resolve, interval/​num_requests*1000));74 }7576 /​/​Simulate 1 extra request from same IP address after limit has been reached.77 request78 .get('/​rate-limit/​check')79 .set('X-Forwarded-For', '192.168.1.1')80 .expect(429, done);81 });82});

Disclaimer: Following code snippets and related information have been sourced from GitHub and/or generated using AI code generation tools. LambdaTest takes no responsibility in the accuracy of the code and is not liable for any damages.

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Power Your Software Testing with AI and cloud

Test Intelligently and ship faster. Deliver unparalleled digital experiences for real world enterprises.

Start Free Testing