REST APIs power the modern web. Behind every mobile app, SaaS dashboard, and third-party integration is an HTTP API sending JSON back and forth. Knowing how to test those APIs — quickly and thoroughly — is one of the highest-leverage skills a developer, QA engineer, or even a sysadmin can have.
This guide covers the complete API testing workflow: understanding HTTP fundamentals, sending requests with cURL, using browser-based tools, validating responses, handling authentication, and building repeatable test suites. Whether you just need to fire off a quick one-liner or you're building a full regression suite, you'll find what you need here.
Quick Reference: HTTP Methods
| Method | Purpose | Has Body? | Idempotent? |
|---|---|---|---|
GET | Retrieve a resource | No | Yes |
POST | Create a resource | Yes | No |
PUT | Replace a resource entirely | Yes | Yes |
PATCH | Partially update a resource | Yes | No |
DELETE | Remove a resource | Optional | Yes |
HEAD | Same as GET but no body returned | No | Yes |
OPTIONS | Describe allowed methods (CORS preflight) | No | Yes |
1 HTTP Status Codes You Must Know
Before writing a single test, internalize the status code ranges. An API is only as trustworthy as its status codes — a response that returns 200 OK with an error message in the body is a sign of a poorly designed API.
2xx — Success
| Code | Meaning | When You See It |
|---|---|---|
200 | OK | Successful GET, PUT, PATCH, DELETE |
201 | Created | Successful POST that created a resource |
204 | No Content | Successful DELETE or action with no response body |
206 | Partial Content | Range request (file downloads, streaming) |
3xx — Redirects
| Code | Meaning | Notes |
|---|---|---|
301 | Moved Permanently | Update your URL; method may change to GET |
302 | Found (Temporary Redirect) | Temporary; method may change to GET |
307 | Temporary Redirect | Same as 302, but method is preserved |
308 | Permanent Redirect | Same as 301, but method is preserved |
4xx — Client Errors
| Code | Meaning | Common Cause |
|---|---|---|
400 | Bad Request | Malformed JSON, missing required field |
401 | Unauthorized | Missing or invalid authentication token |
403 | Forbidden | Authenticated but lacking permission |
404 | Not Found | Resource doesn't exist or wrong URL |
405 | Method Not Allowed | Sending POST to a GET-only endpoint |
409 | Conflict | Duplicate creation, optimistic locking failure |
422 | Unprocessable Entity | Valid JSON but fails validation rules |
429 | Too Many Requests | Rate limit exceeded |
5xx — Server Errors
| Code | Meaning | What It Means for You |
|---|---|---|
500 | Internal Server Error | Bug on the server side |
502 | Bad Gateway | Upstream service returned an invalid response |
503 | Service Unavailable | Server is overloaded or down for maintenance |
504 | Gateway Timeout | Upstream service took too long to respond |
2 Testing APIs with cURL
cURL is the universal tool for making HTTP requests from the command line. It ships on macOS, Linux, and Windows 10+. Every API testing workflow should include fluency with cURL — it requires no setup, runs anywhere, and is scriptable.
Basic GET Request
# Simple GET request
curl https://api.example.com/users
# Show response headers and body
curl -i https://api.example.com/users
# Show only the response headers
curl -I https://api.example.com/users
# Follow redirects automatically
curl -L https://api.example.com/users
# Verbose output (full request + response headers)
curl -v https://api.example.com/users
Sending JSON Data (POST / PUT / PATCH)
# POST with JSON body
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "email": "alice@example.com"}'
# PUT to replace a resource
curl -X PUT https://api.example.com/users/42 \
-H "Content-Type: application/json" \
-d '{"name": "Alice Smith", "email": "alice@example.com"}'
# PATCH to update a single field
curl -X PATCH https://api.example.com/users/42 \
-H "Content-Type: application/json" \
-d '{"email": "newalice@example.com"}'
# DELETE a resource
curl -X DELETE https://api.example.com/users/42
Reading JSON from a File
For larger payloads, keep your JSON in a file and reference it with @:
# payload.json
{
"name": "Alice",
"role": "admin",
"permissions": ["read", "write", "delete"]
}
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d @payload.json
Setting Headers
# Multiple headers
curl https://api.example.com/data \
-H "Accept: application/json" \
-H "X-Api-Version: 2" \
-H "X-Request-ID: abc-123"
Query Parameters
# URL-encode parameters with --data-urlencode
curl -G https://api.example.com/search \
--data-urlencode "q=hello world" \
--data-urlencode "limit=20" \
--data-urlencode "sort=created_at"
# Or just append them to the URL
curl "https://api.example.com/search?q=hello&limit=20"
Pretty-Printing JSON Output
# Pipe through python's json.tool
curl https://api.example.com/users | python3 -m json.tool
# Or use jq (install separately — highly recommended)
curl https://api.example.com/users | jq .
# Extract a specific field with jq
curl https://api.example.com/users | jq '.[0].email'
# Filter an array
curl https://api.example.com/users | jq '.[] | select(.role == "admin")'
Saving the Response to a File
curl https://api.example.com/export -o response.json
# With progress bar
curl https://api.example.com/export -o response.json --progress-bar
Timing a Request
curl -o /dev/null -s -w "
time_namelookup: %{time_namelookup}s
time_connect: %{time_connect}s
time_appconnect: %{time_appconnect}s
time_pretransfer: %{time_pretransfer}s
time_redirect: %{time_redirect}s
time_starttransfer: %{time_starttransfer}s
----------
time_total: %{time_total}s
" https://api.example.com/users
3 Authentication Methods
Most production APIs require authentication. Here's how to handle every common scheme with cURL.
API Key in Header
curl https://api.example.com/data \
-H "X-API-Key: your_api_key_here"
# Some APIs use Authorization header with a custom scheme
curl https://api.example.com/data \
-H "Authorization: ApiKey your_api_key_here"
Bearer Token (OAuth 2.0 / JWT)
curl https://api.example.com/data \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
Basic Authentication
# cURL handles Base64 encoding automatically with -u
curl https://api.example.com/data \
-u username:password
# Prompt for password (avoids storing it in shell history)
curl https://api.example.com/data \
-u username
Getting a Bearer Token First (OAuth 2.0 Client Credentials)
# Step 1: Get the token
TOKEN=$(curl -s -X POST https://auth.example.com/oauth/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_ID&client_secret=YOUR_SECRET" \
| jq -r '.access_token')
# Step 2: Use the token
curl https://api.example.com/data \
-H "Authorization: Bearer $TOKEN"
Cookies
# Save cookies to a file
curl -c cookies.txt https://api.example.com/login \
-X POST -d "username=alice&password=secret"
# Send saved cookies
curl -b cookies.txt https://api.example.com/dashboard
-H "Authorization: Bearer $API_TOKEN" where API_TOKEN is set in your shell environment or a .env file excluded from git.
4 Browser-Based API Testing
Not everyone wants to memorize cURL flags. Browser-based tools let you build and send requests visually, inspect responses with syntax highlighting, and save requests for later — all without installing anything.
Imperial Products REST API Tester
The REST API Tester at Imperial Products is a fast, browser-based tool that lets you:
- Choose any HTTP method (GET, POST, PUT, PATCH, DELETE)
- Add custom request headers with a clean key/value editor
- Paste or type a JSON request body
- See the full response: status code, headers, and formatted body
- Test APIs without CORS issues through the built-in proxy
It's the fastest way to debug an API endpoint when you just need a quick answer — no sign-up, no install, works on any device.
Using Browser DevTools
Your browser's Network tab is an underrated API testing tool. Open DevTools (F12), go to the Network tab, and filter by Fetch/XHR. Every API call your web app makes shows up here with full headers, payloads, and responses. You can right-click any request and select Copy as cURL — a massive timesaver for reproducing requests in the terminal.
# Paste the copied cURL command directly into your terminal
# Browser DevTools → Network → right-click request → Copy as cURL
httpie — a Friendlier CLI Alternative
# Install httpie
pip install httpie
# GET request (much more readable than cURL)
http GET https://api.example.com/users
# POST with JSON (automatic content-type detection)
http POST https://api.example.com/users name="Alice" email="alice@example.com"
# With Bearer token
http GET https://api.example.com/data "Authorization: Bearer $TOKEN"
5 Validating API Responses
Firing a request is only half the job. You need to validate the response — status code, headers, schema, and data — to confirm the API actually behaved correctly.
Checking the Status Code
# Get just the HTTP status code
curl -o /dev/null -s -w "%{http_code}" https://api.example.com/users
# Script: fail if status is not 200
STATUS=$(curl -o /dev/null -s -w "%{http_code}" https://api.example.com/health)
if [ "$STATUS" -ne 200 ]; then
echo "Health check failed with status $STATUS"
exit 1
fi
echo "API is healthy"
Validating JSON Fields with jq
RESPONSE=$(curl -s https://api.example.com/users/1)
# Check a field exists and has the right value
echo $RESPONSE | jq -e '.email == "alice@example.com"'
# Assert the array has the expected length
echo $RESPONSE | jq -e '.items | length == 10'
# Extract and check a nested field
echo $RESPONSE | jq -r '.address.city'
Checking Response Headers
# Get just the Content-Type header
curl -s -I https://api.example.com/users \
| grep -i "content-type"
# Check that rate limit headers are present
curl -s -I https://api.example.com/users \
| grep -i "x-ratelimit"
Response Time Assertions
TIME=$(curl -o /dev/null -s -w "%{time_total}" https://api.example.com/users)
echo "Response time: ${TIME}s"
# Fail if response takes more than 2 seconds
if (( $(echo "$TIME > 2.0" | bc -l) )); then
echo "SLOW: API response exceeded 2s threshold"
exit 1
fi
6 Testing Common API Patterns
Pagination
# Fetch first page
curl "https://api.example.com/posts?page=1&per_page=20" | jq .
# Cursor-based pagination
curl "https://api.example.com/posts?cursor=abc123&limit=20" | jq .
# Check if there are more pages
curl "https://api.example.com/posts?page=1" | jq '.meta.has_next_page'
File Uploads (Multipart Form)
# Upload a single file
curl -X POST https://api.example.com/uploads \
-H "Authorization: Bearer $TOKEN" \
-F "file=@/path/to/image.jpg" \
-F "description=Profile photo"
# Upload multiple files
curl -X POST https://api.example.com/uploads \
-F "files[]=@photo1.jpg" \
-F "files[]=@photo2.jpg"
GraphQL APIs
# GraphQL query via POST
curl -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{
"query": "{ users { id name email } }"
}'
# GraphQL with variables
curl -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d '{
"query": "query GetUser($id: ID!) { user(id: $id) { name email } }",
"variables": { "id": "42" }
}'
Webhook Testing (Receiving Requests)
When testing webhooks, you need a publicly accessible URL that captures incoming requests. Use a service like webhook.site or requestbin.com during development:
# Simulate sending a webhook to your endpoint
curl -X POST https://your-app.com/webhooks/stripe \
-H "Content-Type: application/json" \
-H "Stripe-Signature: t=1623456789,v1=abc123..." \
-d @stripe-event.json
7 Building a Shell-Based Test Suite
For lightweight API regression testing without a heavy framework, a Bash script can cover the essentials. Here's a pattern that works well for smoke testing:
#!/bin/bash
BASE_URL="https://api.example.com"
TOKEN="your_token_here"
PASS=0
FAIL=0
assert_status() {
local description="$1"
local expected="$2"
local actual="$3"
if [ "$actual" -eq "$expected" ]; then
echo " PASS: $description"
((PASS++))
else
echo " FAIL: $description (expected $expected, got $actual)"
((FAIL++))
fi
}
echo "=== Running API Tests ==="
# Test: health check
STATUS=$(curl -o /dev/null -s -w "%{http_code}" "$BASE_URL/health")
assert_status "GET /health returns 200" 200 "$STATUS"
# Test: unauthenticated request returns 401
STATUS=$(curl -o /dev/null -s -w "%{http_code}" "$BASE_URL/users")
assert_status "GET /users without auth returns 401" 401 "$STATUS"
# Test: authenticated request returns 200
STATUS=$(curl -o /dev/null -s -w "%{http_code}" "$BASE_URL/users" \
-H "Authorization: Bearer $TOKEN")
assert_status "GET /users with auth returns 200" 200 "$STATUS"
# Test: create a user
STATUS=$(curl -o /dev/null -s -w "%{http_code}" -X POST "$BASE_URL/users" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"name": "Test User", "email": "test@example.com"}')
assert_status "POST /users returns 201" 201 "$STATUS"
echo ""
echo "Results: $PASS passed, $FAIL failed"
[ "$FAIL" -eq 0 ] || exit 1
Using Newman (Postman CLI Runner)
If you use Postman to build your test collections, Newman lets you run them from the command line — perfect for CI pipelines:
# Install Newman
npm install -g newman
# Run a collection
newman run my-collection.json
# Run with environment file and reporter
newman run my-collection.json \
-e production.json \
--reporters cli,junit \
--reporter-junit-export results.xml
Using k6 for Load Testing
// script.js
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 100, // 100 virtual users
duration: '30s', // for 30 seconds
};
export default function () {
const res = http.get('https://api.example.com/users');
check(res, { 'status was 200': (r) => r.status === 200 });
sleep(1);
}
// Run: k6 run script.js
8 Common API Testing Mistakes to Avoid
Only Testing the Happy Path
Most bugs live in edge cases. For every endpoint, test:
- Missing required fields (expect
400or422) - Invalid field types (string where integer expected)
- Boundary values (empty strings, zero, negative numbers, max integers)
- Unauthorized access (wrong token, expired token, no token)
- Accessing another user's resources (IDOR — Insecure Direct Object Reference)
Not Checking the Response Schema
A 200 status code means the request succeeded — not that the response contains what you expected. Always validate the shape of the response body, especially after server-side changes.
Ignoring Rate Limits
# Check rate limit headers in the response
curl -s -I https://api.example.com/users \
| grep -iE "x-ratelimit|retry-after"
# Typical rate limit headers:
# X-RateLimit-Limit: 1000
# X-RateLimit-Remaining: 987
# X-RateLimit-Reset: 1623456789
Not Testing Idempotency
A PUT or DELETE request should be safe to repeat. Send the same request twice and verify the second response is identical to the first (or 204/404 on the second DELETE — depending on design).
Hardcoding Test Data
Tests that create resources leave orphaned test data unless they clean up after themselves. Always pair a creation test with a deletion step, or use a dedicated test environment that gets reset periodically.
9 API Testing Checklist
Before signing off on any API endpoint, run through this checklist:
- Correct status codes — Does success return
200/201/204? Do errors return the right 4xx/5xx codes? - Response schema — Are all expected fields present with the correct types?
- Authentication — Does the endpoint reject unauthenticated requests with
401? Does it reject unauthorized users with403? - Validation — Does it reject bad input with a clear error message?
- Idempotency — Are PUT and DELETE safe to repeat?
- Pagination — Does the pagination metadata match the actual results?
- Performance — Does the endpoint respond within your SLA (e.g., under 500ms)?
- CORS — Do preflight OPTIONS requests return the correct
Access-Control-Allow-*headers? - Content-Type — Is
Content-Type: application/jsonset on all JSON responses? - Error messages — Are error messages human-readable and free of internal stack traces?
Summary
REST API testing doesn't require expensive tools or complex setups. With cURL, jq, and a solid understanding of HTTP semantics, you can test and validate any API from the command line in minutes. For visual testing and quick debugging, a browser-based tool like the REST API Tester gets you answers instantly.
The most important habit is testing beyond the happy path. Build the muscle of automatically asking: what happens if this field is missing? What if the token is expired? What if I send it twice? APIs that handle edge cases gracefully are the ones that stay stable in production.