How to Pass Headers in Playwright API

Profile picture for user arilio666

In this article, we will be discussing how we can set headers using Playwright.

  • Headers are important to HTTP (Hypertext Transfer Protocol) requests and responses. 
  • They provide additional information about the request or response, such as the content type, encoding, authentication credentials, and cache-control directives.

Let's say we want the response body's content in XML type. We can do this.

 const response = await request.post('https://gorest.co.in/public/v2/users',{
       data: {
           email: "baba@yaga.com",
           name: "John Wick",
           gender: "Male",
           status: "DEAD"
       },headers:{
           "Accept": "application/xml",
           
       }
        
  • Doing this will return a response in XML.
  • In a site called gorest, to post, put, and delete API, we need to use their bearer token as "Authorization" in the header.
  • We need a token to get this message.

Let us see how we can set an authentication token.

    const response = await request.post('https://gorest.co.in/public/v2/users',{
       data: {
           email: "baba@yaga.com",
           name: "John Wick",
           gender: "Male",
           status: "DEAD"
       },headers:{
           "Authorization": "Bearer e48b91bfe1a1156400365fd5f15b6096c622ddd9bd16fa95f18e00dd17f4f48",
           
       }
       });
       
     const responseBody =  JSON.parse(await response.text())
     console.log(responseBody)
     expect(response.status()).toBe(200)
      
      
  • We pass in the token using bearer and then with authorization as the parameter.

Conclusion:

This is how we can set headers in the playwright.