Upload test data files with Newman

Newman supports file uploads so you can send test data (form data or a binary) with an API request. The data file must be located in the same working directory as the collection JSON file you are running. Also, you must include the filename in the src attribute of the request.

The following example shows the exported JSON file for a collection named file-upload. The collection has a single request that uploads a form data file named sample-file.txt in the request body.

// the filename is sample-file.txt
{
	"info": {
		"_postman_id": "9dbfcf22-fdf4-f328-e440-95dbd8e4cfbb",
		"name": "file-upload",
		"description": "A set of `POST` requests to upload files as form data fields",
		"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
	},
	"item": [
		{
			"name": "Form data upload",
			"event": [
				{
					"listen": "test",
					"script": {
						"exec": [
							"const uploadedFile = pm.response.json()?.files['sample-file.txt'];",
							"",
							"pm.test(\"Status code is 200\", () => pm.response.to.have.status(200));",
							"pm.test('File was uploaded correctly', () => pm.expect(uploadedFile).to.match(/^data:application\\/octet-stream;base64/));"
						],
						"type": "text/javascript",
						"packages": {}
					}
				}
			],
			"request": {
				"method": "POST",
				"header": [],
				"body": {
					"mode": "formdata",
					"formdata": [
						{
							"key": "file",
							"type": "file",
							"src": "sample-file.txt"
						}
					]
				},
				"url": {
					"raw": "https://postman-echo.com/post",
					"protocol": "https",
					"host": [
						"postman-echo",
						"com"
					],
					"path": [
						"post"
					]
				},
				"description": "Uploads a file as a form data field to `https://postman-echo.com/post` using a `POST` request."
			},
			"response": []
		}
	]
}

The file sample-file.txt must be present in the same working directory as the collection. Run this collection as usual:

newman run file-upload.postman_collection.json

You'll get a message that the file was uploaded correctly, and the test will pass.

Last modified: 2024/09/16