File Upload in API Testing Using Robot Framework
In Robot Framework API testing, you can upload files using the RequestsLibrary with the files parameter. The API should support multipart/form-data.
Here is a simple working example.
1. Install Required Libraries
pip install robotframework
pip install robotframework-requests
2. Robot Framework File Upload Example
Assume the API endpoint is:
POST https://httpbin.org/post
We want to upload a file named sample.txt.
Project Structure:
RobotFrameworkProject/
│
├── TestCases/
│ └── file_upload.robot
│
└── TestData/
└── sample.txt
3. Create sample.txt
Hello, this is a sample file
for Robot Framework API file upload testing.
4. Create file_upload.robot
*** Settings ***
Library RequestsLibrary
Library OperatingSystem
*** Variables ***
${BASE_URL} https://httpbin.org
${FILE_PATH} ${CURDIR}/../TestData/sample.txt
*** Test Cases ***
Upload File Using API
Create Session api ${BASE_URL}
${file}= Get File For Streaming Upload ${FILE_PATH}
${files}= Create Dictionary
... file=${file}
${response}= POST On Session
... api
... /post
... files=${files}
Log ${response.status_code}
Log ${response.text}
Should Be Equal As Integers ${response.status_code} 200
5. Execute the Test
robot TestCases/file_upload.robot
6. Expected Output
==============================================================================
File Upload
==============================================================================
Upload File Using API | PASS |
------------------------------------------------------------------------------
1 test, 1 passed, 0 failed
==============================================================================
The API response will contain information similar to:
{
"files": {
"file": "Hello, this is a sample file..."
},
"url": "https://httpbin.org/post"
}
7. Upload Multiple Files
You can also upload multiple files in a single API request.
*** Test Cases ***
Upload Multiple Files
Create Session api https://httpbin.org
${file1}= Get File For Streaming Upload ${CURDIR}/../TestData/sample.txt
${file2}= Get File For Streaming Upload ${CURDIR}/../TestData/sample2.txt
${files}= Create Dictionary
... file1=${file1}
... file2=${file2}
${response}= POST On Session
... api
... /post
... files=${files}
Should Be Equal As Integers ${response.status_code} 200
8. Important Keywords
| Keyword | Purpose |
|---|---|
Create Session |
Create API session |
Get File For Streaming Upload |
Read file for upload |
Create Dictionary |
Create multipart file dictionary |
POST On Session |
Send POST request |
Should Be Equal As Integers |
Validate status code |
Important: When uploading files using
multipart/form-data, don't manually set theContent-Typeheader. RequestsLibrary automatically generates the multipart boundary.
You can use the same approach for PDF, CSV, Excel, JSON, XML and image file uploads.

No comments:
Post a Comment