πŸ”Œ API Testing Β· Free cheat sheet

API Testing Decoded

HTTP, REST, SOAP and a real tester's strategy β€” explained the AutomateWithUs way

API Automation Β· Interview Prep Β· REST & SOAP Β· Beginner β†’ Interview-ready

Roadmap

BlockWhat we coverTime
A Β· FoundationsWhat an API is, API vs Web Service, rate limits15 min
B Β· HTTP AnatomyRequest/response parts, methods, status codes, payload, caching25 min
C Β· REST ThinkingConstraints, resources, URIs, representations20 min
D Β· Testing StrategyWhat to verify, test types, bugs, challenges, tools30 min
E Β· SOAP EssentialsEnvelope, WSDL, contract-first vs last, WS-Security20 min
F Β· Decide & DefendREST vs SOAP decision matrix + rapid-fire round10 min

Block A β€” API Foundations

A1. What is an API?

An Application Programming Interface is a contract that lets one piece of software ask another piece of software to do something β€” without knowing how it is done internally. The caller only knows what to send and what it will get back.

Everyday examples you can quote: payment gateways (Razorpay, Stripe), maps (Google Maps), login with Google/GitHub (OAuth), UPI apps talking to bank servers, weather widgets.

A2. API vs Web Service

PointAPIWeb Service
ScopeAny interface between software componentsAn API exposed over a network
NetworkNot required (e.g. Java Collections API, OS APIs)Always required
StylesLibrary calls, REST, GraphQL, gRPC, WebSocket…Traditionally SOAP, REST, XML-RPC
One-linerEvery web service is an API……but not every API is a web service

A3. Usage limits (rate limiting)

Most public APIs cap how many calls a client can make in a time window, and many bill per call. As a tester you should know the limit, test what happens when it is crossed, and make sure your automation suite does not burn through the quota.

Block B β€” HTTP Anatomy

B1. Parts of a request and a response

Request partPurposeExample
MethodThe actionPOST
URL / URIWhich resourcehttps://gorest.co.in/public/v2/users
HeadersMetadata as key–value pairsAuthorization: Bearer <token>, Content-Type: application/json
Query paramsFilters / pagination?page=2&per_page=20
Body (payload)The actual data being sent{ "name": "Asha", "email": "…" }
Protocol versionHTTP/1.1, HTTP/2Usually handled by the client

A response mirrors it: status line (code + reason), headers (Content-Type, Cache-Control, Set-Cookie…), and an optional body. The data you care about is the payload; everything wrapped around it (headers, auth, TLS) is transport.

B2. HTTP methods β€” the full picture

MethodUsed forSafe?Idempotent?Has body?
GETRead a resourceYesYesNo
POSTCreate / trigger processingNoNoYes
PUTReplace a resource completelyNoYesYes
PATCHUpdate part of a resourceNoNot guaranteedYes
DELETERemove a resourceNoYesOptional
HEADSame as GET, headers onlyYesYesNo
OPTIONSWhich methods/CORS rules are allowedYesYesNo
Interview Trap

Safe = does not change server state. Idempotent = calling it once or ten times leaves the server in the same state. Interviewers love asking β€œIs DELETE idempotent?” β†’ Yes; the second call may return 404, but the state does not change further.

B3. PUT vs POST β€” with a real example

Gorest Resource Map

POST /public/v2/users -> create a new user (server assigns id)

GET /public/v2/users -> list users

GET /public/v2/users/{id} -> read one user

PUT /public/v2/users/{id} -> replace that user's full record

PATCH /public/v2/users/{id} -> change only the fields you send

DELETE /public/v2/users/{id} -> remove that user

Can GET be used to create something? Technically a badly designed server could do it, but it breaks HTTP semantics: GET must be safe, can be cached, prefetched and bookmarked β€” so creation belongs to POST (or PUT when the client decides the id).

B4. Status code families

FamilyMeaningCodes you must know
1xxInformational100 Continue
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirection301 Moved Permanently, 304 Not Modified
4xxClient mistake400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable, 429 Too Many Requests
5xxServer failure500 Internal Error, 502 Bad Gateway, 503 Unavailable, 504 Gateway Timeout

B5. Payload size and caching

Block C β€” Thinking in REST

C1. What REST really is

REST (Representational State Transfer) is an architectural style, not a protocol. It models everything as a resource identified by a URI, and uses standard HTTP methods to act on it. A service that follows these rules is called RESTful.

C2. The six constraints (say these confidently)

C3. Resources, URIs and representations

Key Takeaway

Good URI design uses nouns, not verbs: POST /orders β€” not POST /createOrder. The HTTP method already is the verb.

Block D β€” API Testing Strategy

D1. What & why

API testing validates the business layer directly β€” functionality, reliability, performance and security β€” by sending requests and checking responses, with no UI involved.

BenefitWhy it matters in a real project
Shift-left by defaultEndpoints exist before screens, so logic bugs surface before any UI is built
Quick and steady runsNothing to render or locate, so suites finish in seconds with little flakiness
Works with any stackPlain JSON/XML on the wire β€” Java, TypeScript, Python or Postman can all test it
Speeds up UI testsSeed a learner and an enrolment through the API, then open the UI straight at the screen under test
Reaches hidden pathsSend values the UI would block β€” negative numbers, missing fields, huge strings

D2. The verification checklist

For every endpoint, walk through this list. It doubles as your interview answer for β€œWhat do you check in an API test?”

D3. Designing the test β€” five-phase lifecycle

PhaseWhat happens
Arrange (setup)Get token, create test data, set base URL and headers
Act (execute)Fire the request; log request and response
Assert (verify)Compare actual vs expected β€” status, body, schema, time
ReportMark pass / fail / blocked; attach logs to Allure/HTML report
TeardownDelete created data so the next run starts clean

Inputs are designed with the same techniques you use in manual testing: equivalence partitioning, boundary values (string length, number ranges, page size), negative data (missing fields, wrong types, invalid enum), and combinations of optional parameters.

D4. A complete test in Playwright + TypeScript

tests/api/user-lifecycle.spec.ts
import { test, expect } from '@playwright/test';
 
const BASE = 'https://gorest.co.in/public/v2';
const headers = { Authorization: `Bearer ${process.env.GOREST_TOKEN}` };
 
test('create β†’ read β†’ delete a user', async ({ request }) => {
  // Arrange
  const payload = {
    name: 'AWU Learner',
    email: `awu_${Date.now()}@mail.test`,
    gender: 'female',
    status: 'active',
  };
 
  // Act
  const created = await request.post(`${BASE}/users`, { headers, data: payload });
 
  // Assert
  expect(created.status()).toBe(201);
  const user = await created.json();
  expect(user).toMatchObject(payload);
  expect(typeof user.id).toBe('number');
 
  const fetched = await request.get(`${BASE}/users/${user.id}`, { headers });
  expect(fetched.ok()).toBeTruthy();
 
  // Teardown
  const removed = await request.delete(`${BASE}/users/${user.id}`, { headers });
  expect(removed.status()).toBe(204);
});
Running 1 test using 1 worker
  βœ“  user-lifecycle.spec.ts β€Ί create β†’ read β†’ delete a user (1.4s)
  1 passed

D5. Types of API testing

TypeQuestion it answers
FunctionalDoes each endpoint do what the spec says?
ValidationIs the product right β€” data accuracy, schema, business rules?
Integration / E2EDo multiple APIs (and the UI) work together in a flow?
Load / PerformanceHow does it behave at expected and peak traffic?
Security / PenetrationAuth bypass, injection, data exposure, broken access control
FuzzDoes random/malformed input crash it or leak info?
ReliabilityDoes it give consistent results over repeated runs?
ContractDo provider and consumer still agree on the schema?
DocumentationDoes the Swagger/OpenAPI doc match actual behaviour?

D6. Bugs API testing typically finds

D7. Real challenges (and how you handle them)

Real-world headacheWhat an AWU tester does
Leftover test dataUnique values per run (timestamps) plus teardown calls
Tokens that expire mid-runFetch once in global setup; refresh on 401
Calls that depend on each otherChain them: create β†’ read the id β†’ update β†’ delete
Too many optional fieldsPairwise combinations instead of every permutation
Deciding input valuesSpec + EP/BVA, stored in JSON fixture files
Nothing visual to look atSwagger, server logs and request/response attachments in the report

D8. API vs Unit vs UI testing

UnitAPIUI
WhoDevelopersQA / SDET (devs too)QA / SDET
BoxWhite boxMostly black / grey boxBlack box
ScopeOne function/class in isolationBusiness logic via endpointsEnd-user journeys, look & feel
SpeedMillisecondsFastSlowest
WhenBefore the buildOnce service is deployedOnce screens are ready

D9. Tools worth naming

Postman / Newman (manual + CLI runs), Playwright request fixture (TypeScript), REST Assured (Java), SoapUI / ReadyAPI (SOAP & REST), JMeter / k6 (load), Swagger UI (exploration). Mention what you have used and why.

Block E β€” SOAP Essentials

E1. What SOAP is

SOAP (Simple Object Access Protocol) is an XML-based messaging protocol with strict rules. Platform- and language-independent, it is still common in banking, insurance, telecom and government integrations. It usually travels over HTTP POST, but can also use SMTP or other transports.

E2. Message structure

ElementRequired?Role
EnvelopeYes β€” rootMarks the start/end of the message; namespace defines SOAP version
HeaderOptional (max one)Metadata: security tokens, transaction ids, routing
BodyYesThe actual request or response data
FaultInside Body, on errorfaultcode, faultstring, detail
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:acc="http://bank.example/accounts">
  <soap:Header>
    <acc:AuthToken>abc123</acc:AuthToken>
  </soap:Header>
  <soap:Body>
    <acc:GetBalance>
      <acc:AccountId>AWU-1001</acc:AccountId>
    </acc:GetBalance>
  </soap:Body>
</soap:Envelope>

E3. Rules every SOAP message follows

E4. WSDL and the two development approaches

A WSDL (Web Services Description Language) file is the machine-readable contract: operations, input/output messages, data types and endpoint address. Import it into SoapUI and requests are generated for you.

Contract-first (top-down)Contract-last (bottom-up)
OrderWrite WSDL/XSD β†’ generate codeWrite code β†’ generate WSDL
ProsStable contract; client & server teams work in parallelQuick to start; easy for devs
ConsMore upfront effortContract changes whenever code changes; clients wait
Preferred forEnterprise / multi-team integrationsSmall internal services

E5. Security, strengths and weak spots

Block F β€” REST or SOAP? Decide & Defend

Decision factorRESTSOAP
NatureArchitectural styleProtocol
FormatsJSON, XML, text, HTML…XML only
ContractOptional (OpenAPI/Swagger)Formal (WSDL)
StateStatelessCan be stateful
CachingGET responses cacheableNot cacheable by default
SecurityHTTPS + OAuth/JWTHTTPS + WS-Security
TransactionsHandled by the appWS-AtomicTransaction
BandwidthLightweightHeavy envelope overhead
Typical usePublic, mobile, web & social APIsBanking, payments, telecom, legacy enterprise
Key Takeaway

One-line answer: choose REST for simplicity, speed and broad client support; choose SOAP when the contract, message-level security and transactional reliability matter more than speed.

Interview Questions & Answers

Q1. Is REST stateless? What does that mean?

Yes. Every request carries its own auth and context; the server stores no client session between calls.

Q2. Difference between 401 and 403?

401 = you are not authenticated (no/invalid token). 403 = you are authenticated but not allowed.

Q3. What is a payload?

The actual business data in the request/response body β€” separate from headers and transport details.

Q4. What does OPTIONS return?

The methods and CORS rules allowed on a resource, usually via the Allow / Access-Control-Allow-* headers.

Q5. Why is PATCH not guaranteed idempotent?

It describes a change, not a final state β€” e.g. β€œincrement balance by 10” gives a different result each time.

Q6. What is schema validation?

Checking the response structure β€” keys, types, required fields β€” against a JSON Schema or contract.

Q7. What is a WSDL?

An XML contract describing a SOAP service's operations, messages, types and endpoint.

Q8. When does an API return 204?

Success with no body β€” common after DELETE or an update that returns nothing.

Q9. How do you handle auth in an automation suite?

Generate the token once in setup, store it in env/config, inject via headers; never hard-code secrets.

Q10. How do APIs change without breaking clients?

Versioning (/v1, /v2), deprecation notices and sunset dates; testers keep regression suites per version.

Want to learn this live?

Small batches, real projects, mock interviews included. Sit in on a free demo class first.

See all coursesBook a mock interview