API Testing
Masterclass

Learn the fundamentals of APIs and master Postman

πŸš€ Try Interactive API Playground πŸ“š REST Assured Tutorial (Java)

Table of Contents

01

Understanding APIs

What is an API?

An Application Programming Interface (API) is a set of rules and protocols that allows different software applications to communicate with each other. Think of it as a waiter in a restaurant who takes your order (request) to the kitchen (server) and brings back your food (response).

Request

The client sends a request to the server asking for data or an action to be performed.

Processing

The server receives the request, processes it, and prepares an appropriate response.

Response

The server sends back the response with the requested data or confirmation of the action.

πŸ’‘ Real-World Example

When you check the weather on your phone, the app sends an API request to a weather service. The service processes your location and sends back current weather data. You never see this happeningβ€”it's all behind the scenes!

02

HTTP Methods

The Five Essential HTTP Methods

HTTP methods define the type of action you want to perform on a resource. Here are the most common ones:

GET

Retrieve data from a server. Like viewing a webpage or fetching user information.

POST

Create new data on the server. Like submitting a form or creating a new user account.

PUT

Update existing data by replacing it entirely. Like updating all fields of a user profile.

PATCH

Partially update existing data. Like changing just the email address of a user.

DELETE

Remove data from the server. Like deleting a user account or a post.

// Example API requests using different methods

GET https://api.github.com/users/octocat
// Retrieves GitHub user information

GET https://randomuser.me/api/
// Gets a random user profile

POST https://httpbin.org/post
// Echo service that returns your POST data

GET https://dog.ceo/api/breeds/image/random
// Returns a random dog image URL

GET https://api.coindesk.com/v1/bpi/currentprice.json
// Gets current Bitcoin price
03

HTTP Status Codes

Understanding Server Responses

Every API response includes a status code. For QA, these are the first checkpoint for any bug.

Code Status Meaning for Testers
200 OK Standard success response for GET, PUT, or PATCH.
201 Created Resource successfully created (POST). Check if the ID is returned.
204 No Content Success, but empty body. Common for DELETE.
400 Bad Request Invalid input (e.g., missing field, wrong data type). Check your payload.
401 Unauthorized Authentication failed. Token missing, invalid, or expired.
403 Forbidden Authenticated, but no permission. (e.g., User trying to access Admin data).
404 Not Found Endpoint URL is wrong or resource ID doesn't exist.
422 Unprocessable Entity Validation error. Data format is correct (JSON), but logic is wrong (e.g., "Duplicate Email").
429 Too Many Requests Rate limit hit. Slow down your tests.
500 Internal Server Error Backend crash or unhandled exception. Report to developers.
502 Bad Gateway Invalid response from upstream server.
503 Service Unavailable Server overloaded or down for maintenance.
504 Gateway Timeout Upstream server took too long to respond.
04

Try It Yourself

Interactive API Request Builder

Make a real API request and see how it works! We'll use free testing APIs.

⚠️ Browser Limitation: Some APIs may show CORS errors in browsers. This is a security feature. The APIs listed in the "Free APIs for Practice" section below all work! For unrestricted testing, use Postman desktop app.

Response will appear here...

🎯 Try These Working Examples (No CORS Issues!)

GET Dog Image: https://dog.ceo/api/breeds/image/random

GET Random User: https://randomuser.me/api/

GET Activity Idea: https://www.boredapi.com/api/activity

GET Bitcoin Price: https://api.coindesk.com/v1/bpi/currentprice.json

GET Request Test: https://httpbin.org/get

POST Echo Test: https://httpbin.org/post
Body: {"name": "Test User", "message": "Hello API!"}

Understanding CORS (Why Some APIs Don't Work in Browsers)

CORS stands for Cross-Origin Resource Sharing. It's a security feature built into web browsers that prevents websites from making requests to different domains without permission.

The Problem

When you try to call an API from a webpage (like this tutorial), the browser checks if the API allows requests from this domain. If not, it blocks the request with a CORS error.

The Solution

Use Postman! Postman is a desktop application that doesn't have CORS restrictions. It can call any API without browser security limitations.

The APIs listed in this tutorial that work in browsers are specifically configured to allow CORS. Most real-world APIs require tools like Postman for testing.

This is exactly why Postman is the industry standard for API testing!

Ready for Hands-On Practice?

Try our interactive API Playground with pre-configured endpoints and real-time testing!

Launch API Playground β†’
05

Getting Started with Postman

What is Postman?

Postman is a powerful tool for testing and developing APIs. It provides a user-friendly interface to send requests, examine responses, and organize your API tests into collections.

Installation

Download Postman from postman.com/downloads and install it on your computer. It's available for Windows, Mac, and Linux.

Create an Account

Sign up for a free Postman account to sync your work across devices and collaborate with team members.

Explore the Interface

Familiarize yourself with the sidebar (collections), the request builder (center), and the response viewer (bottom).

Making Your First Request in Postman

Open a New Request

Click the "+" button or "New" β†’ "HTTP Request" to create a new request tab.

Choose HTTP Method

Select the method from the dropdown (GET, POST, PUT, etc.). Start with GET for simplicity.

Enter the URL

Type or paste the API endpoint URL. Example: https://api.github.com/users/github

Add Headers (Optional)

Go to the "Headers" tab to add headers like Content-Type: application/json

Add Body (For POST/PUT)

If sending data, go to "Body" β†’ "raw" β†’ select "JSON" and enter your JSON data.

Send the Request

Click the blue "Send" button and view the response below, including status code, time, and size.

Save to Collection

Click "Save" to add this request to a collection for future use and organization.

πŸš€ Pro Postman Features

Collections: Group related API requests together for better organization.

Environment Variables: Store values like API keys or base URLs that you can reuse across requests.

Tests: Write JavaScript code to automatically verify that responses are correct.

Documentation: Generate beautiful API documentation automatically from your collections.

06

Free APIs for Practice

Test Your Skills with These Free APIs

No authentication required - perfect for learning!

GitHub API

GET https://api.github.com/users/github

Get information about any GitHub user

Random User

GET https://randomuser.me/api/

Generate random user data for testing

Dog API

GET https://dog.ceo/api/breeds/image/random

Random dog pictures (always a good idea!)

Bored API

GET https://www.boredapi.com/api/activity

Get random activity suggestions

HTTP Bin (Testing)

POST https://httpbin.org/post

Echo service to test POST requests

CoinDesk API

GET https://api.coindesk.com/v1/bpi/currentprice.json

Current Bitcoin price index

REST Countries

GET https://restcountries.com/v3.1/name/india

Information about any country

IP API

GET https://ipapi.co/json/

Your IP address and location info

JSON Placeholder

GET https://jsonplaceholder.typicode.com/posts

Fake blog posts for testing

πŸ’‘ Pro Tip

Start with simple GET requests to these APIs. Once comfortable, try the HTTPBin service which echoes back whatever you send - perfect for testing POST, PUT, and DELETE methods!

HTTPBin endpoints you can use:

β€’ https://httpbin.org/get (test GET)

β€’ https://httpbin.org/post (test POST)

β€’ https://httpbin.org/put (test PUT)

β€’ https://httpbin.org/delete (test DELETE)

07

API Testing Best Practices

Test All Methods

Don't just test GET requests. Make sure to verify POST, PUT, PATCH, and DELETE operations work correctly.

Check Status Codes

Always verify that you're getting the expected status codes for both successful and error scenarios.

Validate Response Data

Check that the response structure and data types match what you expect from the API documentation.

Handle Errors Gracefully

Test how the API responds to invalid data, missing parameters, and authentication failures.

Use Environment Variables

Store API keys, base URLs, and tokens as variables to easily switch between development and production.

Document Your Tests

Add descriptions to your requests and organize them in collections with clear names.

// Example Postman Test Script

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Response has user data", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('name');
    pm.expect(jsonData).to.have.property('email');
});

pm.test("Response time is less than 500ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});
08

Essential Concepts

Authentication in Detail

Most modern APIs require authentication. For QA/SDETs, understanding how to generate and pass these credentials is crucial.

1. API Keys

What is it? A unique string generated by the server. It verifies who is calling the API (Project/App identification).

How to Test: Usually passed as a header or query parameter.

// Header
x-api-key: 12345-abcde-67890

// Query Param
GET /users?api_key=12345-abcde

2. Bearer Tokens (JWT)

What is it? A "JSON Web Token" generated after a user logs in. It contains user details (claims) encoded in Base64Url.

How to Test: Pass in the Authorization header with the prefix Bearer.

Authorization: Bearer eyJhbGciOiJIUzI1NiIsIn...

Tip: Decode tokens at jwt.io to see user roles/expiry.

3. OAuth 2.0

What is it? The industry standard for authorization (e.g., "Login with Google"). It uses "Access Tokens" to grant limited access without sharing passwords.

QA Focus: Check token expiry. If you get a 401 Unauthorized, the token expired. Use a "Refresh Token" to get a new one.

4. Basic Auth

What is it? Old-school method. Username and password joined by a colon (user:pass) and Base64 encoded.

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

Request Headers

Headers provide additional information about the request. Common headers include:

Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json
User-Agent: Postman/10.0.0

Query Parameters

Parameters appended to URLs to filter, sort, or paginate data:

https://api.example.com/users?page=2&limit=10&sort=name

// Breaking it down:
?        Start of query parameters
page=2   Get page 2 of results
&        Separator between parameters
limit=10 Show 10 items per page
sort=name Sort results by name

Request Body

Data sent with POST, PUT, and PATCH requests, typically in JSON format:

{
  "firstName": "Jane",
  "lastName": "Doe",
  "email": "[email protected]",
  "age": 28,
  "isActive": true
}

Response Structure

API responses typically include status codes, headers, and a body with data or error information.

// Successful Response (200 OK)
{
  "status": "success",
  "data": {
    "id": 123,
    "name": "John Doe"
  }
}

// Error Response (404 Not Found)
{
  "status": "error",
  "error": {
    "code": "NOT_FOUND",
    "message": "Resource not found"
  }
}
09

Advanced Concepts

Pagination Strategies

When dealing with large datasets, APIs return data in chunks instead of all at once.

Offset-Based Pagination

Skip a certain number of items and return the next batch.

// Page 3 with 10 items per page
GET /api/items?page=3&limit=10

// Response includes pagination metadata
{
  "data": [...],
  "pagination": {
    "page": 3,
    "limit": 10,
    "total": 150,
    "totalPages": 15
  }
}

Cursor-Based Pagination

Use a cursor to track position. Better for real-time data.

// Response includes cursor for next page
{
  "data": [...],
  "nextCursor": "eyJpZCI6MTIzfQ==",
  "hasMore": true
}

// Use cursor in next request
GET /api/posts?cursor=eyJpZCI6MTIzfQ==&limit=20

Rate Limiting

APIs limit requests to prevent abuse and ensure fair usage.

// Rate limit headers in response
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1642780800

// 429 Too Many Requests
{
  "error": "Rate limit exceeded",
  "retryAfter": 3600
}

API Versioning

Versioning ensures new changes don't break existing applications.

URL Path Versioning

/api/v1/users

Most common approach

Header Versioning

Accept: app/vnd.api.v2+json

Keeps URLs clean

Query Parameter

/api/users?version=2

Simple but less common

Idempotency

An idempotent operation produces the same result no matter how many times it's executed.

Idempotent: GET, PUT, DELETE

These operations can be safely retried

NOT Idempotent: POST

Creates new resource each time

// Make POST idempotent
POST /api/payments
Idempotency-Key: unique-key-123

Webhooks

Server pushes updates to your app when events occur instead of you polling.

// Register webhook
POST /api/webhooks
{
  "url": "https://myapp.com/webhook",
  "events": ["payment.success"]
}

// Server sends POST when event occurs
POST https://myapp.com/webhook
{
  "event": "payment.success",
  "data": {...}
}

Caching

Reduce server load by caching frequently accessed data.

Cache-Control: public, max-age=3600
ETag: "33a64df5"

// Client checks if cached version is still valid
If-None-Match: "33a64df5"

// Server returns 304 if unchanged