# Created on savesnippets.com ยท https://savesnippets.com/K1roPD3stIptov import mimetypes import requests from pathlib import Path def upload_file( url: str, file_path: str | Path, *, field: str = "file", extra: dict[str, str] | None = None, headers: dict[str, str] | None = None, ) -> requests.Response: file_path = Path(file_path) mime = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream" with file_path.open("rb") as f: files = {field: (file_path.name, f, mime)} return requests.post(url, files=files, data=extra or {}, headers=headers or {}, timeout=60) resp = upload_file( "https://api.example.com/avatar", "/tmp/avatar.png", extra={"user_id": "42"}, headers={"Authorization": "Bearer XYZ"}, ) resp.raise_for_status() print(resp.json())