Rayrun

What is the correct way to send a POST request with data using Playwright?

Answer

Sending POST Requests with Playwright

When sending a POST request with Playwright, you can pass the data object in a few ways.

JSON Data

If your data is an object, Playwright will serialize it to a JSON string and set the content-type header to application/json. Here's how you can do it:

await request.post('https://ray.run/api/createBook', {
  data: {
    title: 'Book Title',
    author: 'John Doe',
  }
});

Form Data

If you need to send form data, use the form option. The data will be encoded with application/x-www-form-urlencoded encoding.

await request.post('https://ray.run/api/findBook', {
  form: {
    title: 'Book Title',
    author: 'John Doe',
  }
});

File Upload

For file uploads, use the multipart option. Provide an object with file information like name, mime type, and content.

await request.post('https://ray.run/api/uploadFile', {
  multipart: {
    file1: fs.createReadStream('/path/to/file1.txt'),
    file2: fs.createReadStream('/path/to/file2.txt'),
  }
});

Remember, the data and form options were added in Playwright version 1.17, and the multipart option in version 1.26. Make sure your Playwright version supports these options.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.