Rayrun
← Back to Discord Forum

How to structure POST with multipart form-data

Hi all, I'm trying to emulate this POST request which I can do in Postman using APIRequestContext.post but I must be missing something as I can't seem to get it in the right shape. Can anyone advise on how to structure the multipart data and what headers would be required? Many thanks in advance! https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-post

image.png

This thread is trying to answer question "How to structure the multipart data and what headers would be required for a POST request using `APIRequestContext.post`?"

4 replies

See if this helps answer your problem. https://playwrightsolutions.com/making-a-post/

@butchmayhew Unfortunately not, no. My example is trickier because as well as uploading the file, I need to send the key value pairs shown in the screenshot (taxYear, title, entityType, ref).

The multipart parameter for APIRequestContext.post will accept either a ReadStream or a Buffer for the file but won't accept any additional key/value pairs in the object. So using this method I can upload my file but I can't send the key/values.

Conversely, the form parameter for sending form data will accept my key value pairs but will not accept my file stream (it only accepts types of string, number or boolean).

The post function won't accept both a multipart and a form parameter in one request, it will only accept one. The test fails if you attempt to send both: Error: apiRequestContext.post: Only one of 'data', 'form' or 'multipart' can be specified

So I still don't have a solution to POST both the file and the key value pairs in one request. Is there something I'm missing here?

Update: OK, it turns out I had a problem in one of our existing helper functions for doing POST requests, it was getting in the way with the request headers 🤦‍♀️ After working that out, I have now got the request working with multipart as below 🙌

const multipart = {
    file: stream,
    title: "Test Questionnaire",
    ref: "testing,
    taxYear: 2022,
    entityType: "individual"
  };
const response = await apiContext.post(`/${getTestVersion()}/form-templates/import`, { multipart });```

Related Discord Threads

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 [email protected].