Testfilelab
Home / Guides / Test API File Handling
Guide

How to Test File Uploads in a REST API

Test file upload endpoints with valid and invalid files, verify multipart requests and confirm that your API handles errors correctly.

Introduction

API file upload testing checks whether an endpoint accepts the right files, enforces validation rules and returns predictable responses. It covers request formatting, file size limits, MIME types, authentication, error handling and the behaviour of the uploaded file after the request succeeds.

A file upload endpoint can work correctly through your website but fail when called directly. Testing the API independently helps uncover problems with request headers, multipart form data, validation and server configuration.

This guide covers practical tests using curl, Postman, Python and JavaScript.

Prepare your API test cases

Before sending requests, identify the endpoint, authentication requirements and expected behaviour.

Test caseExpected result
Valid file and valid requestUpload succeeds
Missing file fieldClear validation error
Unsupported file typeRequest rejected
File exceeds the size limitRequest rejected with an appropriate error
Incorrect MIME typeRequest rejected if it violates validation rules
Unauthenticated requestAuthentication error
Malformed multipart requestRequest rejected
Unsupported HTTP methodAppropriate method error
Multiple files when only one is allowedRequest rejected or handled according to the API contract

Use the API's documented status codes and response format as the source of truth. Different applications may use different codes for similar validation failures.

Test a file upload with curl

The curl command-line tool lets you send multipart form-data requests without using a browser.

Example:

curl -X POST "https://your-domain.com/api/upload" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -F "file=@sample.pdf"

Replace the example endpoint, token and filename with values from your test environment.

Note: This is a sample request for testing your own upload API. Testfilelab does not provide a file upload service, so replace the example URL with your own endpoint.

When using -F, curl builds the multipart request, including the appropriate content-type boundary. Avoid manually setting the overall Content-Type: multipart/form-data header unless you also correctly manage the boundary.

Check the response for:

  • HTTP status code.
  • Error or success message.
  • Uploaded file identifier, if returned.
  • Any documented metadata such as filename, size or detected type.
  • Whether the file is actually stored and available through the expected workflow.

Do not use production credentials or upload sensitive files during routine testing.

Test file uploads in Postman

Postman provides a visual way to test multipart file uploads.

  1. Create a request using the HTTP method required by your endpoint, commonly POST.
  2. Enter your upload API URL.
  3. Configure the required authentication.
  4. Open Body and select form-data.
  5. Add the field name expected by the API, such as file.
  6. Change the field type from Text to File, then select a test file.
  7. Send the request and inspect the response.

If the endpoint expects additional fields, such as a document category or record ID, include them as specified in the API contract.

Test both successful uploads and failure scenarios. For example, submit an unsupported file type, omit the file field or use a file larger than the permitted limit.

Verify file validation and MIME detection

An API must not rely only on a filename or a MIME type supplied by the client.

Test the following cases:

  • A valid file with an allowed extension and expected content.
  • An unsupported extension.
  • A file whose extension does not match its content.
  • A declared MIME type that does not match the actual file.
  • A malformed or truncated file.
  • A zero-byte file, if empty files are not allowed.

For example, rename plain text to report.pdf and submit it to a PDF-only endpoint. If the API claims to validate PDF content, it should not accept the file merely because its name ends in .pdf.

Where applicable, check file signatures and use format-aware validation. A signature check can help identify a format, but it does not guarantee that a file is complete or safe.

See the MIME types reference for common media types and the file validation testing guide for additional validation cases.

Test file uploads with Python requests

The Python requests library can send a file as multipart form data.

import requests

url = "https://your-domain.com/api/upload"
headers = {
    "Authorization": "Bearer YOUR_TOKEN"
}

with open("sample.pdf", "rb") as file:
    response = requests.post(
        url,
        headers=headers,
        files={"file": ("sample.pdf", file, "application/pdf")},
        timeout=30
    )

print("Status:", response.status_code)
print("Response:", response.text)

Replace the URL, authentication and field name with your API's actual requirements.

Note: This is a sample request for testing your own upload API. Testfilelab does not provide a file upload service, so replace the example URL with your own endpoint.

This example supplies application/pdf as the declared content type. It does not prove the file is a valid PDF; the server should perform the required content validation.

For automated tests, add assertions for the expected status code and response structure instead of relying only on printed output.

Test file uploads with JavaScript fetch

In browser-based JavaScript, use FormData to send a file to the endpoint.

const formData = new FormData();
formData.append("file", fileInput.files[0]);

const response = await fetch("/api/upload", {
  method: "POST",
  body: formData
});

const result = await response.json();

console.log("Status:", response.status);
console.log("Response:", result);

Here, fileInput represents an existing file input element. Adapt the endpoint and response parsing to your application.

Note: This is a sample request for testing your own upload API. Testfilelab does not provide a file upload service, so replace the example URL with your own endpoint.

Important: Do not manually set the multipart Content-Type header when sending FormData through fetch. The browser must add the boundary parameter for the request.

If your API uses bearer-token authentication, include the required authorization header according to your security design. Avoid exposing secret credentials in public client-side code.

Test file size limits and large uploads

Confirm the maximum upload size enforced by your API and test files below, at and above that boundary.

For a hypothetical 10 MB limit using binary units:

TestFile sizeWhat to verify
Below limit9 MBUpload follows the expected success path
At limit10 MBBoundary behaviour matches the documented rule
Above limit11 MBRequest is rejected if the maximum is 10 MB

These examples use binary sizes: 1 MB = 1,048,576 bytes. Your application's limit may use a different unit or apply a different boundary rule, so verify the exact configured value.

Test the complete request path. A reverse proxy, web server, application framework and API handler may each enforce their own limits. The effective limit is determined by the configuration and request path, not just one setting.

For ready-made test files, use Testfilelab's files by size. You can also review the file upload limits guide.

Understand common API status codes

Use this table as a testing reference, then confirm the expected behaviour in your API documentation.

Status codeCommon meaningWhat to check
200 OKRequest succeededResponse body and upload result
201 CreatedA resource was createdResource identifier and metadata
400 Bad RequestRequest is malformed or invalidError details and validation behaviour
401 UnauthorizedAuthentication is missing or invalidAccess is denied
403 ForbiddenCaller lacks permissionFile is not accepted
413 Content Too LargeRequest exceeds a size limitSize-limit handling
415 Unsupported Media TypeMedia type is unsupportedFormat restrictions
422 Unprocessable ContentRequest content fails application validationField-level or file-level errors
500 Internal Server ErrorUnexpected server failureSafe error response and server logs

The exact status code depends on the API contract and where the failure occurs. For example, a reverse proxy may reject an oversized request before the application can return its usual validation response.

Do not treat a 200 or 201 response alone as proof that the uploaded file was processed correctly. Verify the expected result.

Check authentication, storage and error handling

A successful upload request is only one part of the test.

Also verify that:

  • Requests without valid credentials are handled as documented.
  • Users cannot upload files to records they are not authorised to access.
  • Invalid files are not passed to downstream processing.
  • Duplicate requests behave as expected.
  • Failed uploads do not leave unintended partial files or records.
  • Successful uploads return the correct identifier or metadata.
  • Error responses do not expose server paths, secrets or stack traces.
  • Uploaded files are accessible only through the intended permissions and delivery rules.

Run these tests in an authorised development or staging environment.

Automate API upload tests

Once manual tests pass, add repeatable checks to your API test suite or CI pipeline.

For each scenario, define the request, expected status code, response fields and any expected storage or processing result.

A useful automated suite includes:

  • One valid upload for every supported format.
  • Missing-file and malformed-request cases.
  • Invalid extension and MIME mismatch cases.
  • Files below, at and above the size limit.
  • Authentication and permission checks.
  • A check that rejected files are not processed.
  • A check that successful files can be retrieved or processed as expected.

Keep test files deterministic and avoid using real customer documents. Stable sample files make it easier to reproduce failures across local, staging and CI environments.

API file upload testing checklist

  • Valid multipart requests succeed.
  • The API uses the expected file field name.
  • Authentication and permissions are enforced.
  • Unsupported formats and MIME mismatches are rejected.
  • File-size boundaries are tested.
  • Missing and malformed requests return documented errors.
  • Status codes and response bodies match the API contract.
  • Failed uploads do not leave unintended partial data.
  • Successful uploads are stored and processed as expected.
  • Automated tests run reliably in the intended environment.

Frequently asked questions

API file upload testing verifies that an endpoint accepts valid files, rejects invalid requests, enforces size and format rules, and returns the expected status codes and response data.

Use the method and endpoint specified by the API, typically POST, and send the file using multipart/form-data. You can do this with curl, Postman, Python requests or JavaScript FormData.

It depends on the API contract. Common choices include 400, 415 and 422, while an oversized request may return 413. Document the intended behaviour and test it consistently.

Send files below, at and above the configured limit. Verify both the response and whether the file was stored. Account for any reverse proxy or web server limits that may reject the request before it reaches the application.

No. Client-provided MIME types can be incorrect or manipulated. The server should apply appropriate validation based on the application's supported formats and security requirements.

Start Testing Your File Upload API

Use valid and invalid sample files to verify your API's multipart requests, file validation, size limits and error responses. Test the endpoint directly, confirm the expected status codes and automate repeatable checks before releasing changes.

Get Free Test Files