how to load test api with login k6
Build With Amaobi
0:00 / 0:00
how to load test api with login k6
93 просмотра · 2 недели назад
Build With Amaobi
5 подписчиков
93 просмотра · 2 недели назад
How do you load test an API that requires login? In this k6 tutorial you'll write your first k6 script against a real FastAPI backend: sign up, log in, reuse the JWT token, and update data with 10 virtual users, plus thresholds that fail the test when your API gets slow.
Most k6 tutorials test a demo site with no authentication. This one tests a real API the way real users use it.
🔗 Code (API + k6 scripts + Postman collection):
https://github.com/victorex27/k6-load...
📄 Written version of this tutorial:
What you'll learn
• How to install k6 and run your first load test
• How to load test signup and login endpoints with unique test users
• How to extract a JWT from the login response and send it as a Bearer token (correlation)
• How to use checks to validate response data, not just status codes
• How to set thresholds (p95 less than 500ms, error rate less than 1%) so k6 passes or fails your test
• How to tag requests so you can see exactly which endpoint is slow
• How to ramp load up and down with stages, and use the k6 web dashboard
Chapters
0:00 How do you load test an API with login?
0:47 What we're building (FastAPI + k6)
1:23 Tour of the API: signup, login, JWT, items
2:14 Testing the endpoints in Postman
3:59 Installing k6 and writing your first script
9:41 Load testing signup and login with k6
9:54 Using the JWT token on protected endpoints
14:10 k6 thresholds: pass or fail your load test
15:14 Breaking the API on purpose (p95 goes red)
17:56 Realistic load test: stages + log in once per user
19:17 Recap
FAQ
Q: Can k6 test APIs that need authentication?
A: Yes. Call your login endpoint, read the token with res.json('access_token'), and send it in an Authorization: Bearer header on every protected request.
Q: How do I avoid duplicate users when load testing signup?
A: Build a unique email per request from __VU (virtual user number), __ITER (iteration) and Date.now().
Q: What is p95 in k6?
A: The response time that 95% of requests were faster than. It's a better health signal than the average.
Q: What is a k6 threshold?
A: A pass/fail rule like http_req_duration: ['p(95) less than 500']. If any threshold fails, k6 exits with a non-zero code, so CI fails.
Stack: k6 v2, Python, FastAPI, SQLAlchemy, SQLite, JWT, bcrypt, Postman
#k6 #loadtesting #fastapi