When getting a file-like object from an API request, and copying it to a file, is there any way to determine what the file type was from the file-like object?
In the below example, I'm copying the response to testing.pdf
because I just happen to know that the document in question was a PDF.
However, I'm trying to write a script that will take in a series of document IDs and run a bulk download from the source system (Oracle Aconex in this case).
This might be a question more aimed at the Aconex API, but I don't know much about Python's request library or how it works in the background, so thought I'd ask if there's something I'm missing.
import requests
import shutil
# Set aconex username and password
user_pass = (username, password)
# Document ID
doc_id = "xxxxxxxxxxxx"
# API Connection String
download_docs_string = "https://uk1.aconex.co.uk/api/projects/xxxxxxxx/register/" + doc_id
# API request ~ content is returned as bytes
response = requests.get(download_docs_string, auth = user_pass, stream = True)
# Copy contents of file-like object to new file
with open("testing.pdf", "wb") as f:
response.raw.decode_content = True
shutil.copyfileobj(response.raw, f)