Search code examples
playwrightplaywright-typescript

Playwright: cant set Host header for APIRequestContext


I'm currently trying to automate sending API calls to Gmail API.

  • Sending requests with Postman works fine. Using Fetch library works fine.
  • Sending the same request using APIRequestContext in Playwright returns a 404 HTTP error. The same error i get if i set the wrong Host header in Postman.

What i'm trying to do is to create an APIRequestContext instance, set Host header to it and then send a GET request.

import { APIRequestContext, expect, test } from "@playwright/test";

let apiContextGmailInbox: APIRequestContext;

apiContextGmailInbox = await playwright.request.newContext({
    // All requests we send go to this API endpoint.
    baseURL: "https://gmail.googleapis.com/gmail/v1/users",
    extraHTTPHeaders: { Host: "gmail.googleapis.com", }
});

test("test get last email body via API", async ({page}) => {
    const mailContext = await apiContextGmailInbox.get(
                                     "/{USER_EMAIL}/messages/", 
                                     { headers: { Host: "gmail.googleapis.com",},
    });
    expect(mailContext.status()).toBe(401);
});

As i dont have auth token, i should get 401. But i'm getting 404. I guess that's because somehow the request does not include Host header even if i set one. Or am i missing something?


Solution

  • Because for some reason its not picking the BaseURL.

    Try this:

    apiContextGmailInbox.get("https://gmail.googleapis.com/gmail/v1/users/{USER_EMAIL}/messages/")