automating-api-testing
Test automate API endpoint testing including request generation, validation, and comprehensive test coverage for REST and GraphQL APIs. Use when testing API contracts, validating OpenAPI specifications, or ensuring endpoint reliability. Trigger with phrases like "test the API", "generate API tests", or "validate API contracts".
What this skill does
# API Test Automation
## Overview
Automate comprehensive API endpoint testing for REST and GraphQL APIs including request generation, response validation, schema compliance, authentication flows, and error handling. Supports Supertest (Node.js), REST-assured (Java), httpx/pytest (Python), Postman/Newman collections, and Pact for consumer-driven contract testing.
## Prerequisites
- API testing library installed (Supertest, REST-assured, httpx, or Postman/Newman)
- API specification file (OpenAPI/Swagger YAML/JSON or GraphQL SDL)
- Target API running in a test environment with seeded data
- Authentication credentials or API keys for protected endpoints
- JSON Schema validator (Ajv, jsonschema, or built-in framework assertions)
## Instructions
1. Read the API specification and extract all endpoints:
- Parse OpenAPI spec to catalog every path, HTTP method, request schema, and response schema.
- For GraphQL APIs, introspect the schema to list queries, mutations, and subscriptions.
- Document authentication requirements per endpoint (API key, Bearer token, OAuth, none).
2. Generate test cases for each endpoint:
- **Success cases**: Send valid requests matching the schema and assert 200/201 responses.
- **Validation errors**: Send requests with missing required fields, wrong types, and out-of-range values; assert 400 responses.
- **Authentication**: Test with valid, expired, and missing credentials; assert 200, 401, and 403 respectively.
- **Not found**: Request non-existent resources; assert 404 responses.
- **Idempotency**: Send the same PUT/DELETE request twice and verify consistent behavior.
3. Validate response structure against schemas:
- Assert response Content-Type matches expected (application/json, etc.).
- Validate response body against the OpenAPI response schema using JSON Schema validation.
- Check response headers (Cache-Control, Rate-Limit headers, CORS headers).
- Verify pagination metadata (total count, page number, next/previous links).
4. Test CRUD lifecycle for resource endpoints:
- Create a resource (POST) and capture the ID.
- Read it back (GET) and verify all fields match.
- Update it (PUT/PATCH) and verify changes persisted.
- Delete it (DELETE) and verify subsequent GET returns 404.
5. Test error handling and edge cases:
- Send excessively large payloads and verify 413 or graceful rejection.
- Send requests with unsupported Content-Types and verify 415.
- Test rate limiting by sending rapid sequential requests.
- Verify error response format is consistent (standard error schema).
6. For GraphQL APIs, test specifically:
- Valid queries return expected data shapes.
- Invalid queries return descriptive error messages.
- Query depth limiting prevents deeply nested abuse queries.
- Mutation input validation matches schema constraints.
7. Generate a test coverage report mapping endpoints to test cases.
## Output
- API test files organized by resource in `tests/api/`
- Request/response examples for API documentation
- Schema compliance report for each endpoint
- Endpoint coverage matrix showing tested vs. untested endpoints and methods
- CI pipeline step running API tests against staging environment
## Error Handling
| Error | Cause | Solution |
|-------|-------|---------|
| Connection refused | API server not running or wrong base URL | Verify server is up with a health check before test suite starts; check `BASE_URL` config |
| 401 on all requests | Authentication token expired or misconfigured | Refresh token in test setup; verify `Authorization` header format; check token scopes |
| Schema validation fails unexpectedly | API response includes extra fields not in spec | Update OpenAPI spec to include new fields; use `additionalProperties: true` if expected |
| Test data conflicts | Another test modified or deleted the resource | Use unique test data per test; create resources in `beforeEach`; avoid shared fixtures |
| Rate limit hit during test run | Too many requests in quick succession | Add delays between requests or use authenticated sessions with higher limits; run tests serially |
## Examples
**Supertest REST API test suite:**
```typescript
import request from 'supertest';
import { app } from '../src/app';
describe('GET /api/products', () => {
it('returns a paginated product list', async () => {
const res = await request(app)
.get('/api/products?page=1&limit=10')
.set('Authorization', `Bearer ${token}`)
.expect(200) # HTTP 200 OK
.expect('Content-Type', /json/);
expect(res.body.data).toBeInstanceOf(Array);
expect(res.body.data.length).toBeLessThanOrEqual(10);
expect(res.body.meta).toMatchObject({ page: 1, limit: 10 });
});
it('returns 401 without authentication', async () => { # HTTP 401 Unauthorized
await request(app).get('/api/products').expect(401); # HTTP 401 Unauthorized
});
});
describe('POST /api/products', () => {
it('creates a product with valid data', async () => {
const res = await request(app)
.post('/api/products')
.set('Authorization', `Bearer ${token}`)
.send({ name: 'Widget', price: 9.99, category: 'tools' })
.expect(201); # HTTP 201 Created
expect(res.body).toMatchObject({ name: 'Widget', price: 9.99 });
expect(res.body.id).toBeDefined();
});
it('returns 400 for missing required fields', async () => { # HTTP 400 Bad Request
await request(app)
.post('/api/products')
.set('Authorization', `Bearer ${token}`)
.send({ name: 'Widget' }) // missing price
.expect(400); # HTTP 400 Bad Request
});
});
```
**GraphQL API test:**
```typescript
it('fetches user by ID', async () => {
const query = `query { user(id: "1") { id name email } }`;
const res = await request(app)
.post('/graphql')
.send({ query })
.expect(200); # HTTP 200 OK
expect(res.body.data.user).toMatchObject({ id: '1', name: 'Alice' });
expect(res.body.errors).toBeUndefined();
});
```
## Resources
- Supertest: https://github.com/ladjs/supertest
- REST-assured (Java): https://rest-assured.io/
- httpx (Python): https://www.python-httpx.org/
- Newman (Postman CLI):
- OpenAPI specification: https://spec.openapis.org/oas/v3.1.0
- Ajv JSON Schema validator: https://ajv.js.org/
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.