How to Execute POST Requests in Playwright

HOME

What is POST Request?

npm install playwright

import { defineConfig } from '@playwright/test';

export default defineConfig({
  reporter: 'html',
});

import { test, expect } from '@playwright/test';

 test('API Testing - POST with Playwright', async ({ request }) => {

     // Perform a POST request
     const postResponse = await request.post('https://jsonplaceholder.typicode.com/users', {
       data: {
         title: 'Manager',
         body: 'Test',
         userId: 10,
       }
     }); 

     // Check the response status code
     expect(postResponse.status()).toBe(201);

      // Parse the response data
     const postResponseBody = await postResponse.json();
     console.log(postResponseBody);

     // Validate the response
     expect(postResponseBody).toHaveProperty('title', 'Manager');
     expect(postResponseBody).toHaveProperty('body', 'Test');
     expect(postResponseBody).toHaveProperty('userId', 10);
   });
import { test, expect } from '@playwright/test';
test('API Testing - POST with Playwright', async ({ request }) 
 const postResponse = await request.post('https://jsonplaceholder.typicode.com/users', {
       data: {
         title: 'Manager',
         body: 'Test',
         userId: 10,
       }
     }); 
expect(postResponse.status()).toBe(201);
const postResponseBody = await postResponse.json();
console.log(postResponseBody);

The assertions verify that the response contains expected data.

expect(postResponseBody).toHaveProperty('title', 'Manager');
expect(postResponseBody).toHaveProperty('body', 'Test');
expect(postResponseBody).toHaveProperty('userId', 10);

npx playwright test api_post_tests.spec.ts

npx playwright show-report