To send a file as multipart/form-data in pytest, you can use the requests library to make the HTTP request with the file attached to the request. requests is a popular Python library for making HTTP requests, and it works well with pytest for testing APIs that require file uploads.

Here's an example of how you can send a file using multipart/form-data in pytest:

  1. First, make sure you have the requests library installed. You can install it using pip:
pip install requests
  1. Write a pytest test function that sends the file using requests. Here's an example test function that uploads a file to an API endpoint:
import requests import pytest @pytest.mark.parametrize("file_path", [ "path/to/your/file.txt", # Replace with the path to your file # Add more file paths if needed ]) def test_upload_file(file_path): url = "" # Replace with the API endpoint URL with open(file_path, "rb") as file: files = {"file": (file_path, file, "multipart/form-data")} response =, files=files) # Assertions based on the response, e.g. check status code or response content assert response.status_code == 200 assert "success" in response.json()
  1. In this example, the test_upload_file function takes the file path as a parameter and sends it as part of the files parameter in the call. The file is opened in binary mode using "rb" to read the file data. The "multipart/form-data" content type is automatically set by requests when you use the files parameter.

  2. Replace the url variable with the actual API endpoint URL where you want to upload the file.

  3. Run your pytest test suite:


The test function will be executed, and the file will be uploaded to the specified API endpoint. Make sure to handle the file upload on the server-side as well.

Remember that in a real-world scenario, you should use a mock or a test-specific server endpoint to avoid making actual API calls during testing. You can use libraries like pytest-mock to help with mocking the server responses. Additionally, consider testing various edge cases and error scenarios in your tests to ensure robustness.

Have questions or queries?
Get in Touch