|

Day 7: API Testing — Validate Backend Without a Browser

This is Day 7 of the 21-Day Playwright with TypeScript Challenge. One lesson per day. Zero to production-ready in 3 weeks.

🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy.


Playwright has a built-in API client. No need for Axios, Supertest, or RestAssured. Test your REST APIs and combine with UI tests in the same framework.

Contents

Basic API Requests

test('GET users', async ({ request }) => {
  const response = await request.get('/api/users');
  expect(response.ok()).toBeTruthy();
  expect(response.status()).toBe(200);
  
  const body = await response.json();
  expect(body.users.length).toBeGreaterThan(0);
  expect(body.users[0]).toHaveProperty('email');
});

test('POST create user', async ({ request }) => {
  const response = await request.post('/api/users', {
    data: { name: 'Test', email: 'test@example.com' }
  });
  expect(response.status()).toBe(201);
  
  const user = await response.json();
  expect(user.id).toBeDefined();
});

test('PUT update user', async ({ request }) => {
  const response = await request.put('/api/users/1', {
    data: { name: 'Updated Name' }
  });
  expect(response.status()).toBe(200);
});

test('DELETE user', async ({ request }) => {
  const response = await request.delete('/api/users/1');
  expect(response.status()).toBe(204);
});

🚀 Level Up Your Playwright

From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.

Authentication

test('authenticated API call', async ({ request }) => {
  // Login
  const login = await request.post('/api/auth/login', {
    data: { email: 'admin@test.com', password: 'pass' }
  });
  const { token } = await login.json();
  
  // Authenticated request
  const response = await request.get('/api/admin/users', {
    headers: { 'Authorization': 'Bearer ' + token }
  });
  expect(response.ok()).toBeTruthy();
});

Hybrid Pattern: API + UI

test('create via API, verify in UI', async ({ page, request }) => {
  // Fast: create data via API
  const res = await request.post('/api/products', {
    data: { name: 'Widget', price: 29.99 }
  });
  const product = await res.json();
  
  // Validate: check UI renders correctly
  await page.goto('/products/' + product.id);
  await expect(page.getByText('Widget')).toBeVisible();
  await expect(page.getByText('$29.99')).toBeVisible();
});

Week 1 complete! You now know: installation, locators, assertions, interactions, POM, fixtures, API testing. Tomorrow starts Week 2: network interception.

🎓 Master Playwright End to End

Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.