Search code examples
filekarate

Sending a file in the body of a POST request in Karate


I am having some difficulties getting a request to work as expected in Karate where I use a .json file in the body of my POST request. I have tried to define it as both a form field and as a multipart file. I assume I'm not doing this correctly because neither of them are getting me the same result as my CURL command. I removed a few of the secret variables, they for sure work in context of the CURL command from Postman.

curl --location 'https://{{QA_URL}}/v1/lists/10790' \
--header 'accept: application/json' \
--header 'x-key: {{KEY}}' \
--header 'x-secret: {{SECRET}}' \
--form 'file=@"/Downloads/tmp-test4.json"'

This is my karate scenario in which I do a GET call to retrieve a collection of lists then secondly; to do a POST request to update my specific list - with the couple of failed attempts at declaring the file. The file is located in the file location referenced in my read steps. Thank you for any and all help!

Scenario: GET list public api tests
* def requestBody = read("file:src/test/java/json/User/Request/updateListDetails.json")
* set requestBody.notes = randomString

Given path '/v1' + '/lists/'
And header Content-Type = 'application/json'
And header x-key = Key
And header x-secret = Secret
When method GET
* def listId = response.lists[2].id

Given path '/v1' + '/lists/' + listId
And header accept = 'application/json'
And header Content-Type = 'multipart/form-data'
And header x-key = Key
And header x-secret = Secret
#And form field file = read("file:src/test/java/json/User/Request/updateListDetails.json")
#And multipart field file = { read: 'file:src/test/java/json/User/Request/updateListDetails.json', filename: 'updateListDetails.json', contentType: 'multipart/form-data' }
#And request requestBody
When method POST
Then status 200

Solution

  • Thank you for the suggestion Peter, below is the code that was able to get it working for me. My declaration for the file was too granular, I needed to just use multipart file and now it's working just as the curl command is.

    Scenario: GET list public api tests
    * def requestBody = 
    read("file:src/test/java/json/User/Request/updateListDetails.json")
    * set requestBody.notes = randomString
    
    Given path '/v1' + '/lists/'
    And header Content-Type = 'application/json'
    And header x-key = Key
    And header x-secret = Secret
    When method GET
    * def listId = response.lists[2].id
    
    Given path '/v1' + '/lists/' + listId
    And header accept = 'application/json'
    And header Content-Type = 'multipart/form-data'
    And header x-key = Key
    And header x-secret = Secret
    And multipart file file = { read: 'file:src/test/java/json/User/Request/updateListDetails.json', filename: 'updateListDetails.json', contentType: 'multipart/form-data' }
    When method POST
    Then status 200