While exploring k6 for performance testing, I discovered that it can also be used for API automation. After further research, I decided to write this blog to share my findings.
API automation is crucial for modern software development, ensuring performance, reliability, and scalability. While many tools exist, k6 stands out for its efficiency in load testing and performance monitoring. Originally designed for performance testing, k6 is also powerful for API automation, offering a simple scripting interface with deep insights into API behavior.
In this blog, we’ll explore:
- What k6 is and why it’s useful
- How to set up k6 for API automation
- Writing API test scripts in k6
- Running and analyzing test results
By the end, you’ll have a strong foundation to automate API testing with k6 effectively.
What is k6?
k6 is an open-source load testing tool built for developers and DevOps engineers. It enables testing of APIs and microservices under realistic conditions with high performance and minimal resource usage. Unlike tools like JMeter, k6 uses JavaScript (ES6), making it easier to write and maintain test scripts.
Why Choose k6 for API Automation?
- Lightweight & Scalable: Handles thousands of virtual users efficiently.
- Scripting with JavaScript: Uses ES6 syntax, making it developer-friendly.
- Powerful Metrics: Provides detailed insights into API performance.
- Integrations: Works with CI/CD pipelines, Prometheus, Grafana, and more.
Setting Up k6 for API Automation
Before writing scripts, let’s install k6 and set up the environment.
Installation
For different OS:
- Mac (via Homebrew):
brew install k6
- Windows (via Chocolatey):
choco install k6
- inux (via APT):
sudo apt update && sudo apt install k6
Verify installation by running:
k6 version
Writing API Test Scripts in k6
k6 scripts are written in JavaScript and executed using the k6 runtime. Below is a simple example:
Basic GET Request
Create a file named test.js and add the following script:
import http from 'k6/http';
import { check } from 'k6';
export default function () {
let response = http.get('https://jsonplaceholder.typicode.com/posts/1');
check(response, {
'is status 200': (r) => r.status === 200,
'body contains userId': (r) => r.body.includes('"userId": 1'),
});
}
Run the test:
k6 run test.js
POST Request with JSON Payload
import http from 'k6/http';
import { check } from 'k6';
export default function () {
let payload = JSON.stringify({
title: 'Automated API Test',
body: 'Testing k6 for API automation',
userId: 1
});
let params = {
headers: { 'Content-Type': 'application/json' }
};
let response = http.post('https://jsonplaceholder.typicode.com/posts', payload, params);
check(response, {
'is status 201': (r) => r.status === 201,
'response contains title': (r) => r.json().title === 'Automated API Test'
});
}
Handling Headers and Authentication
For APIs requiring authentication, use headers:
let headers = {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
};
let response = http.get('https://api.example.com/protected', { headers });
Running API Tests with k6
To execute tests, use:
k6 run test.js
For higher load testing, specify virtual users (VUs) and duration:
k6 run --vus 10 --duration 30s test.js
This simulates 10 users making requests for 30 seconds.
Output Example
✓ is status 200
✓ body contains userId
checks.........................: 100.00% ✓ 2 ✗ 0
http_req_duration..............: avg=120.5ms min=100ms max=150ms
Advanced API Testing with k6
Parameterized Testing
To test with multiple inputs:
let testCases = [
{ id: 1, expectedTitle: 'Post 1' },
{ id: 2, expectedTitle: 'Post 2' }
];
export default function () {
testCases.forEach(tc => {
let response = http.get(`https://jsonplaceholder.typicode.com/posts/${tc.id}`);
check(response, {
[`Title is correct for ID ${tc.id}`]: (r) => r.json().title === tc.expectedTitle
});
});
}
Performance Testing with Thresholds
Set performance criteria:
import { sleep } from 'k6';
export let options = {
thresholds: {
http_req_duration: ['p(95)<500'] // 95% of requests should be < 500ms
}
};
export default function () {
let response = http.get('https://jsonplaceholder.typicode.com/posts/1');
sleep(1);
}
Integrating k6 with CI/CD
k6 integrates with GitHub Actions, Jenkins, and GitLab CI/CD.
Example: GitHub Actions Workflow
name: API Test
on:
push:
branches:
- main
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Install k6
run: sudo apt update && sudo apt install -y k6
- name: Run k6 test
run: k6 run test.js
Conclusion
k6 is a powerful tool for API automation and performance testing, offering an intuitive JavaScript-based approach with scalable execution.
Key Takeaways:
- Lightweight and developer-friendly
- Supports authentication, headers, and payloads
- Ideal for load testing and automation
- Integrates well with CI/CD pipelines
With k6, you can ensure your APIs are fast, reliable, and scalable. Try it out and supercharge your API testing workflow!