Course outline: Tools and specialisms
Module 03 · Tools and specialisms
API testing fundamentals
What an API is, how requests and answers work, and how to test one properly, with the tools to do it.
What you'll be able to do
- Explain what an API is, and tell REST, SOAP and GraphQL apart.
- Read a request (method, address, headers, body) and the status code that comes back.
- Turn one cURL command into a list of API tests, with the status codes to check.
- Test sign-in and permissions: what an API must refuse, and how.
What is an API?
An API (Application Programming Interface: A software intermediary that allows two applications to talk to each other.) is a set of rules and protocols that allows different software applications to communicate with each other. APIs define the methods and data formats that applications can use to request and exchange information, enabling developers to integrate external functionalities without building them from scratch.
Real-life Example (The Restaurant Analogy)
- Customer (User): You, wanting services/data.
- Menu (API Documentation): Lists available services/data and how to request them.
- Waiter (API): The intermediary taking your request to the system (kitchen).
- Kitchen (Server): Processes the request and returns the response (meal).
Software Examples
- Social Media Integration: Apps using Facebook/Twitter APIs for login or sharing.
- Payment Processing: E-commerce sites using Stripe/PayPal APIs for secure transactions.
- Weather Data: Apps using OpenWeatherMap API to fetch forecasts.
Importance in Software Development
- Interoperability: Helps different systems work together seamlessly.
- Efficiency: Saves time with ready-made functions, speeding up development.
- Automation: Enables automation of repetitive tasks, boosting productivity.
- Scalability & Flexibility: Allows apps to grow and adapt easily.
- Innovation: Encourages new apps and services by sharing features.
Types of APIs
1. Web APIs
2. Library APIs
3. Framework APIs
4. Operating System APIs
Web Services
Web Services are services that communicate between machines over a network, typically the internet. They use standardized web protocols (like HTTP) and data formats (like XML (Extensible Markup Language: A markup language for encoding documents in a format that is both human-readable and machine-readable.) or JSON (JavaScript Object Notation: A lightweight data-interchange format.)).
Key takeaway: All Web Services are APIs, but not all APIs are Web Services (e.g., Library or OS APIs don't necessarily use a network).
Examples of Web Services
- Weather Information Services
- Payment Gateways (Stripe, PayPal)
- Social Media Integration Services
APIs vs. Web Services
| Aspect | API | Web Service |
|---|---|---|
| Definition | Set of rules for software communication. | Standardized method for communication over a network. |
| Communication | Various protocols (HTTP, TCP, etc.) | Primarily web protocols (HTTP/HTTPS). |
| Data Formats | Multiple (JSON, XML, etc.) | Typically XML or JSON. |
| Accessibility | Local or remote. | Specifically remote over a network. |
| Implementation | Various styles (REST, SOAP, GraphQL, etc.) | Generally SOAP or REST. |
Web API Architectures
A Web API is an API accessed over the web using HTTP. It's a framework for creating HTTP-based services, often following architectural styles like REST or query languages like GraphQL. It's crucial for distributed systems serving various devices (laptops, mobiles).
REST (Representational State Transfer: An architectural style for designing networked applications.) Architecture
An architectural style using standard HTTP methods, emphasizing statelessness and flexibility. Preferred for web and mobile apps due to simplicity and performance.
How it Works: Client sends HTTP request (GET, POST, PUT, DELETE) to a URI. Server responds with a resource representation (often JSON).
REST Request Structure:
- HTTP Method: GET, POST, PUT, DELETE, PATCH, etc.
- Endpoint/URI: Identifies the resource (e.g., `/users/123`).
- Headers: Metadata (e.g., `Content-Type: application/json`, `Authorization: Bearer [YOUR_TOKEN_HERE]`).
- Query Parameters (Optional): Filter/modify request (e.g., `/users?active=true`).
- Body (Optional): Data payload for POST/PUT/PATCH (usually JSON).
Example Request:
GET /api/users/123 HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer eyJhbGciOiJIU...SOAP (Simple Object Access Protocol: A messaging protocol specification for exchanging structured information.) Protocol
A protocol designed for exchanging structured information, ensuring interoperability across platforms using XML. More rigid than REST.
Uses XML format for messages and can operate over various protocols (HTTP, SMTP).
SOAP Protocol Structure:
- Envelope: Root element defining the message.
- Header (Optional): Application-specific info (e.g., authentication).
- Body: Contains the actual message/call.
- Fault (Optional): Error information.
WSDL (Web Services Description Language: An XML-based interface description language used for describing the functionality offered by a web service.):
An XML-based language describing the service's functionalities, acting as a contract.
Messaging Patterns:
- Request-Response
- One-Way
- Publish-Subscribe
Example SOAP Message:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<soap:Body>
<m:GetUser xmlns:m="http://api.example.com/user">
<m:UserId>123</m:UserId>
</m:GetUser>
</soap:Body>
</soap:Envelope>GraphQL (A query language for APIs and a runtime for fulfilling those queries with your existing data.) Query Language
A query language for APIs developed by Facebook. Allows clients to request exactly the data they need, reducing over-fetching and under-fetching.
How it Works: Client sends a query specifying the structure of the data needed. Server responds with a JSON object matching that structure.
Key Features:
- Declarative Data Fetching: Clients ask for specific fields.
- Single Endpoint: Typically uses a single endpoint (e.g., `/graphql`).
- Strongly Typed Schema: Defines the API's capabilities.
- Real-time Data (Subscriptions): Supports real-time updates.
Example Query:
query {
user(id: "123") {
name
email
posts(last: 5) {
title
createdAt
}
}
}Use Cases:
Complex systems, mobile apps needing efficient data loading, applications with rapidly evolving frontends.
Architecture Comparison
| Aspect | REST | SOAP | GraphQL |
|---|---|---|---|
| Type | Architectural Style | Protocol | Query Language |
| Data Format | JSON, XML, etc. | XML only | JSON |
| Endpoints | Multiple (per resource) | Often Single | Typically Single |
| Data Fetching | Fixed structure (potential over/under-fetching) | Fixed structure | Client specifies needed data |
| Communication | Stateless | Can be Stateful/Stateless | Stateless |
| Security | Transport (HTTPS), OAuth | Built-in WS-Security | Transport (HTTPS), App-level |
| Contract | Less Strict (OpenAPI optional) | Strict (WSDL required) | Strict (Schema required) |
API Testing Overview
API Testing is a type of software testing that validates APIs directly by sending calls, getting output, and checking the system's response. It focuses on the business logic layer, verifying functionality, reliability, performance, and security, rather than the graphical user interface (GUI (Graphical User Interface: Allows users to interact with electronic devices through graphical icons and visual indicators.)).
Types of API Testing
| Type | Description | Example Tool / Focus |
|---|---|---|
| Functional | Validates API works per requirements (endpoints, methods, parameters). | Postman, REST-Assured |
| Performance | Assesses responsiveness & stability under load (latency, throughput). | JMeter, k6, Gatling |
| Security | Identifies vulnerabilities (auth, injection, data exposure). Check OWASP API Security Top 10. | OWASP ZAP, Burp Suite |
| Validation | Confirms API meets business needs & data format/schema. | Schema validation tools, Custom scripts |
| Load | Evaluates behavior under expected user loads. | JMeter, LoadRunner |
| Runtime/Error Detection | Monitors for issues during execution (exceptions, error codes). | APM tools (Datadog, Dynatrace) |
| Interoperability | Ensures seamless interaction with other systems/APIs. | Contract Testing (Pact) |
| Fuzz | Sends random/invalid data to find crashes or security issues. | Fuzzing tools (AFL, Peach Fuzzer) |
HTTP Methods & Status Codes
HTTP (Hypertext Transfer Protocol: The protocol used for transmitting hypermedia documents, such as HTML.) enables client-server communication using a request-response model.
Common HTTP Methods
- GET: Retrieve resource information (Safe method - doesn't change state).
- POST: Send data to create a new resource.
- PUT: Update/replace an entire resource at a specific URI (Idempotent).
- DELETE: Delete a resource identified by the URI.
- PATCH: Partially update a resource (not idempotent by definition: sending "add one copy" twice adds two).
Example Usage (User Profile):
// GET /users/123 - Retrieve user 123's profile
{
"id": 123,
"name": "Alice",
"email": "alice@example.com",
"posts": [ { "postId": 1, "title": "First Post" } ]
}
// POST /users - Create a new user
{ "name": "Bob", "email": "bob@example.com" }
// Response: 201 Created, Location: /users/456
// PUT /users/123 - Replace user 123's data entirely
{ "id": 123, "name": "Alice Smith", "email": "alice.smith@example.com" }
// Response: 200 OK
// PATCH /users/123 - Update only user 123's email
{ "email": "new.alice@example.com" }
// Response: 200 OK
// DELETE /users/123 - Delete user 123
// Response: 204 No ContentHTTP Status Codes
Three-digit codes indicating the outcome of a request:
- 1xx (Informational): Request received, continuing process (e.g., 100 Continue).
- 2xx (Successful): Request successfully received, understood, and accepted (e.g., 200 OK, 201 Created, 204 No Content).
- 3xx (Redirection): Further action needed (e.g., 301 Moved Permanently, 302 Found).
- 4xx (Client Error): Error caused by the client (e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found).
- 5xx (Server Error): Server failed to fulfill a valid request (e.g., 500 Internal Server Error, 503 Service Unavailable).
POST vs. PUT vs. PATCH
| Category | POST | PUT | PATCH |
|---|---|---|---|
| Purpose | Create new resource. | Replace existing resource (or create if not exists). | Partially update existing resource. |
| Idempotency | No (multiple requests create multiple resources). | Yes (multiple requests have same effect). | Not by definition: it depends on the change it describes. |
| Resource URI | Usually applied to a collection URI (e.g., /users). | Applied to a specific resource URI (e.g., /users/123). | Applied to a specific resource URI (e.g., /users/123). |
| Payload | Contains data for the new resource. | Contains the complete new representation. | Contains only the changes to apply. |
API Authentication & Authorization
Authentication (Verifying Identity - Who are you?)
Confirms who the user or system making the request is.
Common Methods:
- API Keys: Simple tokens passed in headers/params. Easy but less secure if exposed.
- Basic Auth: Username/password encoded (Base64), sent in Authorization header. Simple but insecure over HTTP.
- OAuth 2.0: Standard for delegated access (e.g., "Login with Google"). More complex but secure for third-party access.
- JWT (JSON Web Token: A compact, URL-safe means of representing claims to be transferred between two parties.): Compact, self-contained tokens for stateless authentication. Server verifies signature.
- OpenID Connect (OIDC): Identity layer on top of OAuth 2.0.
Authorization (Verifying Permissions - What can you do?)
Determines what actions an authenticated user is allowed to perform.
Common Methods:
- RBAC (Role-Based Access Control: Access decisions based on the roles individual users have as part of an organization.): Permissions based on user roles (Admin, Editor, Viewer).
- ABAC (Attribute-Based Access Control: Access decisions based on attributes associated with the user, resource, environment, etc.): Access based on attributes (user location, time of day, resource sensitivity).
- ACLs (Access Control Lists): Explicit lists of permissions per user/group for specific resources.
- Policy-Based Access Control (PBAC): Uses policies combining attributes and conditions.
Testing Focus: Verify that unauthenticated requests are rejected (401/403), authenticated users can access allowed resources, users cannot access resources they shouldn't (e.g., another user's data), and different roles have appropriate permissions.
API Testing Tools
Various tools assist in designing, testing, documenting, and managing APIs throughout their lifecycle.
Popular Tools:
Swagger / OpenAPI Specification
The OpenAPI Specification (A standard, language-agnostic interface description for RESTful APIs, which allows both humans and computers to discover and understand the capabilities of the service.) (formerly Swagger Specification) defines a standard way to describe REST APIs. Swagger provides tools built around this specification.
Key tools include Swagger UI (interactive documentation), Swagger Editor (design APIs), and Swagger Codegen (generate client/server code).
Visit Swagger.ioSwagger Petstore ExamplePostman
A popular collaborative platform for API development and testing. It simplifies making requests, organizing tests, and sharing work.
Key Features:
- Intuitive Request Builder
- Automated Testing (Collections, Scripts)
- Mock Servers
- Documentation Generation
- Workspaces for Collaboration
- Environment & Global Variables
- Monitoring & Reporting
- API Client for various protocols (REST, SOAP, GraphQL, gRPC)
Installation & Use:
Download from the Postman Downloads page. Use it to create requests, organize them in Collections, write JavaScript tests in the "Tests" tab, and run collections automatically.
Example Postman Test Script:
// Example test in Postman's "Tests" tab
pm.test("Status code is 200", () => {
pm.response.to.have.status(200);
});
pm.test("Response time is less than 200ms", () => {
pm.expect(pm.response.responseTime).to.be.below(200);
});
pm.test("Content-Type header is present", () => {
pm.response.to.have.header("Content-Type");
});
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("expected_string");
});
// Check if a JSON value is equal to something
pm.test("User ID is correct", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.userId).to.eql(123);
});Common Challenges & Best Practices
Effective API testing requires addressing common hurdles and following best practices.
Challenges
- Environment Setup: Configuring test environments mimicking production can be complex.
- Parameter Combinations: Testing all possible input combinations is often infeasible.
- Sequencing Calls: Many API workflows require specific call sequences (e.g., login → create → update).
- Schema Validation: Ensuring responses consistently match the expected schema/contract.
- Managing Test Data: Creating and maintaining realistic and isolated test data.
- Non-Functional Testing: Adequately covering performance, security, and reliability.
- Third-Party APIs: Handling dependencies on external APIs that might be unstable or rate-limited.
Best Practices
- Test Early, Test Often: Integrate API testing into the CI/CD pipeline.
- Focus on Business Logic: Prioritize tests validating core functionalities.
- Use Realistic Data: Employ data similar to production, covering edge cases.
- Validate Status Codes, Response Body, and Headers: Check all parts of the response.
- Implement Contract Testing: Ensure consumer/provider contracts are met (e.g., using Pact).
- Automate Where Possible: Automate regression tests, functional tests, and performance tests.
- Parameterize Tests: Use variables for environments, credentials, and data to make tests reusable.
- Group Tests Logically: Organize tests by feature or workflow (e.g., using Postman Collections).
- Monitor API Health: Use monitoring tools to track performance and errors in production.
Worked example · Cedar Books
The coupon API from one cURL command
A developer hands you one command that applies a coupon through the API of Cedar Books, the Academy's practice shop. Almost everything an API test needs is in it:
curl -X POST https://practice.qaia.io/api/coupons/apply \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"code": "CEDAR10"}'| Part | Here | What it tells the tester |
|---|---|---|
| Method | POST | The call changes something: it applies a code to a basket. Other methods on this address answer 404. |
| Address | /api/coupons/apply | The endpoint. The shop's OpenAPI document (/api/openapi.json) lists its answers: 200, 400, 404 and 422. |
| Authorization | Bearer <token> | Whose basket this is. Without it, each call starts a new, empty basket of its own. |
| Content-Type | application/json | The body is JSON; a body that is not valid JSON must get 400, never a crash. |
| Body | {"code": "CEDAR10"} | The input to vary: valid, expired, used-up, unknown and malformed codes. |
The sign-in token. The token comes from another call: POST /api/auth/login with a demo shopper's email and the password shown on the shop's sign-in page. The answer is JSON with a token field; put it in the header of each later call. Keep real tokens out of bug reports and screenshots: whoever holds one can act as that user.
curl -X POST https://practice.qaia.io/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "shopper.one@cedarbooks.example", "password": "<password>"}'Then put a book in the basket with POST /api/basket/items and the body {"bookId": 1, "qty": 1} (The Cedar Tree, 19.00). Now each code you send has a basket to work on.
The status codes to check.
| Code sent | Status | Why |
|---|---|---|
| CEDAR10, basket 19.00 | 200 | Applied: one coupon line of 1.90, total 17.10 |
| WELCOME5, basket 19.00 | 422 | Understood, but refused by a rule: it needs 25.00 or more |
| SPRING25 | 422 | Refused: the code is used up |
| EXPIRED24 | 422 | Refused: the code has expired, and REQ-06 asks for a clear message |
| HELLO10 | 404 | Well formed, but there is no such code |
| c! or an empty code | 400 | Not a code at all: the request is malformed |
A protected call such as GET /api/orders without a token answers 401. Not every list of status codes shows 422: it means the server understood the request and refuses it by a rule, which is what a refused coupon is, while 400 is for a request that is not well formed. Check which one the API's documentation promises, and test that.
A test list.
- Each row of the table: the status, the message, and after a refusal, the basket left as it was.
- The totals after CEDAR10: the discount is 10% of the subtotal, and the total is the subtotal minus the discount.
- A second code replaces the first, and the same code sent twice gives one line (REQ-03).
- A missing body, a body that is not JSON, a code of a hundred characters: always a 4xx and a plain message.
- The schema: the answer has message (text), coupons (a list of code and amount) and totals (numbers).
- Without a token, the call works on a new, empty basket and never touches the signed-in shopper's basket.
The schema. A schema check compares the shape of each answer with the API's document: every field there, each of the right type. It catches a missing field or a value of the wrong type even when the screen looks right, and a tool can run it on every call.
The 500 to look for. No input from a client should ever get a 500: it means the server failed instead of refusing bad input with a 4xx and a plain message. A 500 that shows a stack trace is worse, because it shows strangers how the server is built. The shop of the API lab has such an answer: find it yourself.
Try it: cURL to API tests · The API lab
Sign in to keep your progress: a tick here lives in this browser only.
Test yourself
Quiz: API testing
10 questions, about 8 minutes. Sign in to take the quiz.
10 questions, about 8 minutes, no time limit. 7 right answers pass, and passing marks the lesson as read. Every new quiz draws new questions.