Python Requests Examples for File Upload, Download, and Validation

This article presents a series of Python requests code snippets demonstrating how to upload and download files, compare contents, process CSV and JSON payloads, verify file size, name, MD5 checksum, MIME type, and handle multiple file uploads in typical backend API scenarios.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Requests Examples for File Upload, Download, and Validation

This guide provides ten practical examples using the Python requests library to perform common file‑related operations in backend development.

1. Upload a file to a server

import requests

def test_upload_file():
    url = "https://api.example.com/upload"
    file_path = "path/to/file.txt"
    with open(file_path, "rb") as file:
        files = {"file": ("file.txt", file)}
        response = requests.post(url, files=files)
        assert response.status_code == 200
        assert response.json()["message"] == "File uploaded successfully"

2. Download a file and save locally

import requests

def test_download_file():
    url = "https://api.example.com/download"
    local_path = "path/to/local/file.txt"
    response = requests.get(url)
    with open(local_path, "wb") as file:
        file.write(response.content)
    assert response.status_code == 200

3. Compare two files' contents

import requests

def test_compare_files():
    url = "https://api.example.com/download"
    local_path = "path/to/local/file.txt"
    remote_path = "path/to/remote/file.txt"
    with open(local_path, "r") as local_file, open(remote_path, "r") as remote_file:
        local_content = local_file.read()
        remote_content = remote_file.read()
    assert local_content == remote_content

4. Read a CSV file and send each row as request parameters

import csv
import requests

def test_send_csv_data():
    url = "https://api.example.com/csv"
    file_path = "path/to/file.csv"
    with open(file_path, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            response = requests.post(url, data=row)
            assert response.status_code == 200

5. Read a JSON file and POST it as the request body

import json
import requests

def test_send_json_data():
    url = "https://api.example.com/json"
    file_path = "path/to/file.json"
    with open(file_path, "r") as file:
        data = json.load(file)
    response = requests.post(url, json=data)
    assert response.status_code == 200

6. Download a file and validate its size

import requests

def test_validate_file_size():
    url = "https://api.example.com/download"
    response = requests.get(url)
    file_size = len(response.content)
    assert file_size == 1024  # assumed size in bytes

7. Upload a file and verify the returned filename

import requests

def test_validate_uploaded_filename():
    url = "https://api.example.com/upload"
    file_path = "path/to/file.txt"
    with open(file_path, "rb") as file:
        files = {"file": ("file.txt", file)}
        response = requests.post(url, files=files)
        assert response.status_code == 200
        assert response.json()["filename"] == "file.txt"

8. Upload multiple files in a single request

import requests

def test_upload_multiple_files():
    url = "https://api.example.com/upload"
    files = [
        ("file", ("file1.txt", open("path/to/file1.txt", "rb"))),
        ("file", ("file2.txt", open("path/to/file2.txt", "rb")))
    ]
    response = requests.post(url, files=files)
    assert response.status_code == 200
    assert len(response.json()["uploaded_files"]) == 2

9. Upload a file and validate its MD5 checksum

import hashlib
import requests

def test_validate_md5_checksum():
    url = "https://api.example.com/upload"
    file_path = "path/to/file.txt"
    with open(file_path, "rb") as file:
        files = {"file": ("file.txt", file)}
        response = requests.post(url, files=files)
        assert response.status_code == 200
    md5_hash = hashlib.md5()
    with open(file_path, "rb") as file:
        while chunk := file.read(8192):
            md5_hash.update(chunk)
    assert response.json()["md5"] == md5_hash.hexdigest()

10. Upload a file and verify its MIME type

import mimetypes
import requests

def test_validate_mimetype():
    url = "https://api.example.com/upload"
    file_path = "path/to/image.jpg"
    with open(file_path, "rb") as file:
        files = {"file": ("image.jpg", file)}
        response = requests.post(url, files=files)
        assert response.status_code == 200
        assert response.json()["mimetype"] == mimetypes.guess_type(file_path)[0]

All URLs and file paths are placeholders; replace them with real endpoints and locations when applying these examples in your own projects.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonBackend Developmentrequests
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.