0

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)
MT0
  • 143,790
  • 11
  • 59
  • 117
  • requests will just return binary data. You'd have to inspect that data to try to determine what it is – DarkKnight May 26 '22 at 10:32
  • Either map the file extension to a mime-type or read the first bytes of the file (which may or may not represent a file signature) and use that to try to determine the mime-type. – MT0 May 26 '22 at 10:33
  • Does this answer your question? [How to find the mime type of a file in python?](https://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python) – MT0 May 26 '22 at 10:35
  • Ok thanks. I'm sure the link answers my question. But I could try reading the first bytes of data. With that said, there is another option of using the script to determine what files the id's map to, and doing it that way. –  May 26 '22 at 10:39

0 Answers0