I am trying to use Playwright to carry out an API test. The simple case is that I am trying to get info on a user. To do this with curl, I can issue the command:
curl --user username:password https://example.com/api/user/id
This will respond with some JSON. Super simple.
I have read through the Playwright docs, watched some YouTube videos and scoured various sources, but can't find out how to replicate this in Playwright!
My requests are consistently getting a response of "403 Forbidden".
In my playwright.config.ts
file, I have added httpCredentials
like so:
import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';
const config: PlaywrightTestConfig = {
[...]
use: {
headless: false,
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'https://example.com',
httpCredentials: {
username: 'username',
password: 'password'
},
[...]
Meanwhile, in my apiExperiment.spec.ts
file:
import {test} from '@playwright/test';
test.describe('Test the API', () => {
test('Get user info', async({request}) => {
let userInfo = await request.post('/api/user/id');
});
});
As I said previously, this just results in "403 Forbidden".
I have tried variations on this theme, like removing the httpCredentials
from the config file, then changing the apiExperiment.spec.ts
file to:
import {test} from '@playwright/test';
test.describe('Test the API', () => {
test('Get user info', async({request}) => {
let userInfo = await request.post('/api/user/id', {
data: {
username: 'username',
password: 'password',
}
});
});
});
and another variation...
import {test} from '@playwright/test';
test.describe('Test the API', () => {
test('Get user info', async({request, browser}) => {
const context = await browser.newContext({
httpCredentials: {username: 'username', password: 'password'}
});
let userInfo = await context.request.post('/api/user/id');
});
});
but to no avail.
Any help with this would be gratefully received.