If the payload you are downloading is binary you would write it like this:

open('my.jpg', 'wb').write(response.content)

Or if it is text:

open('my.txt', 'w').write(response.text)
#print(open("my.txt", "r").read())
Answer from wp78de on Stack Overflow
Top answer
1 of 5
2
I'm executing python script from the command line. · I may be missing some steps below but the general way to install python is as follows. · 1. Install python · https://phoenixnap.com/kb/how-to-install-python-3-windows · 2. Create subdirectory · mkdir servicenowapis · 3. Move to the subdirectory · cd servicenowapis · 4. Create a virtualenv · python-m venv venv · 5. Activate venv · venv\Scripts\activate.bat · 6. Install request module · pip install requests · 7. Copy the script I've provided to the directory · 8. Copy and paste content of Constants.py over import statements · 9. Edit username, password · 9. Edit table_api.py to use Incident number · e.g. · get_file_attachment('INC0000002') · 10. Execute command · python test_api.py ·   · import requests · SERVICENOW_URL = 'https://.service-now.com' · SERVICENOW_USER = '' · SERVICENOW_PWD = '' · DOWNLOAD_DIR = './downloads/' · REQUEST_HEADER = {"json": {"Content-Type": "application/xml", "Accept": "application/json"}, · "png": {"Content-Type": "application/xml", "Accept": "application/png"}, · "xml": {"Content-Type": "application/xml", "Accept": "application/xml"}, · } · ATTACHMENT_API = '/api/now/attachment' · TABLE_API = '/api/now/table' · # TABLE_NAME = 'kb_knowledge' · TABLE_NAME = 'incident' · def get_table_data(table_name, param): · url = SERVICENOW_URL + TABLE_API + '/' + table_name + '?' + param · response = requests.get(url, auth=(SERVICENOW_USER, SERVICENOW_PWD), headers=REQUEST_HEADER.get('json')) · if response.status_code != 200: # if error, then exit · print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:', response.json()) · exit() · return response.json() · def get_attachment_info(sys_id): · url = SERVICENOW_URL + ATTACHMENT_API + '/' + sys_id · response = requests.get(url, auth=(SERVICENOW_USER, SERVICENOW_PWD), headers=REQUEST_HEADER.get('json')) · if response.status_code != 200: # if error, then exit · print(f'Status: {response.status_code}, Headers:{response.headers}') · exit() · return response.json() · def get_attachment(att_sys_id, file_type, download_dir): · url = SERVICENOW_URL + '/' + ATTACHMENT_API + '/' + att_sys_id + '/file' · response = requests.get(url, auth=(SERVICENOW_USER, SERVICENOW_PWD), headers=REQUEST_HEADER.get(file_type)) · if response.status_code != 200: # if error, then exit · print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:', response.json()) · exit() · with open(download_dir, 'wb') as f: · for chunk in response: · f.write(chunk) · def get_file_attachment(record_number): · param = 'sysparm_query=number=' + record_number + '&sysparam_limit=1' · file_info = get_table_data(TABLE_NAME, param).get('result') · if len(file_info) < 1: · print(f'There is no attachment to sys_id:{record_number}') · return · attachment_sys_id = file_info[0].get('sys_id') · param = 'sysparm_query=table_sys_id=' + attachment_sys_id + '&sysparam_limit=1' · kb_attachments = get_table_data('sys_attachment', param) · result = kb_attachments.get('result') · for attach_file in result: · attach_sys_id = attach_file.get('sys_id') · content_type = attach_file.get('content_type').split('/') · file_ext = content_type[1] · file_name = attach_file.get('file_name') · get_attachment(attach_sys_id, file_ext, DOWNLOAD_DIR + file_name) · if __name__ == '__main__': · # get_file_attachment('KB0010062') # knowledge base number · get_file_attachment('INC0000002') · View solution in original post
2 of 5
0
Hi, · please find my points below · APIs are only used to retrieve the data from the instance. It will not download the attachment directly, using API you can get the url of the attachment and when you clicked on the URL it will download the file once you give the credentials.Otherwise use the binary code returned by the API to convert into the attachment file and download into the system from where this API has been called. · RegardsAnkur · Regards,Ankur✨Certified Technical Architect  ||  10x ServiceNow MVP ServiceNow Community Leader
Discussions

python - Flask-RESTful: Using GET to download a file with REST - Stack Overflow
I am trying to write a file sharing application that exposes a REST interface. The library I am using, Flask-RESTful only supports returning JSON by default. Obviously attempting to serve binary d... More on stackoverflow.com
🌐 stackoverflow.com
http - download files with python (REST URL) - Stack Overflow
I am trying to write a script that will download a bunch files from a website that has REST URLs. Here is the GET request: GET /test/download/id/5774/format/testTitle HTTP/1.1 Host: testServer.co... More on stackoverflow.com
🌐 stackoverflow.com
March 1, 2015
Python Rest client api to upload a file - Stack Overflow
I am using Python 2.7. My Rest server side API works fine and I am able to upload a zip file using Postman. I am trying to upload a zip file using Rest client api. I tried requests package, but it is More on stackoverflow.com
🌐 stackoverflow.com
Facing issue while trying to download file using Rest API
Hi All, i was trying to list and download file from a folder. For listing, http://CSurl/otcs/cs.exe/api/v2/nodes/ /nodes where am parsing the json and taking the data id. Then i am giving as input the above received document id to below api http://CSurl/otcs/cs.exe/api/v2/nodes/ /content When ... More on forums.opentext.com
🌐 forums.opentext.com
September 17, 2024
🌐
LearnPython.com
learnpython.com › blog › how-to-download-file-in-python
How to Download a File in Python | LearnPython.com
December 23, 2021 - Any REST API that lets clients access or modify sensitive or critical data must have an authentication system in place. Even if the API is free, the owner may introduce authentication to limit the number of requests per user. For this tutorial, we will fetch and save files in Python from place.dog and randomfox.ca. No authentication is required, so you can reuse the code snippets to download ...
Top answer
1 of 3
10

The approach suggested in the Flask-RESTful documentation is to declare our supported representations on the Api object so that it can support other mediatypes. The mediatype we are looking for is application/octet-stream.

First, we need to write a representation function:

from flask import Flask, send_file, safe_join
from flask_restful import Api

app = Flask(__name__)
api = Api(app)

@api.representation('application/octet-stream')
def output_file(data, code, headers):
    filepath = safe_join(data["directory"], data["filename"])

    response = send_file(
        filename_or_fp=filepath,
        mimetype="application/octet-stream",
        as_attachment=True,
        attachment_filename=data["filename"]
    )
    return response

What this representation function does is to convert the data, code, headers our method returns into a Response object with mimetype application/octet-stream. Here we use send_file function to construct this Response object.

Our GET method can be something like:

from flask_restful import Resource

class GetFile(Resource):
    def get(self, filename):
        return {
            "directory": <Our file directory>,
            "filename": filename
        }

And that's all the coding we need. When sending this GET request, we need to change the Accept mimetype to Application/octet-stream so that our API will call the representation function. Otherwise it will return the JSON data as by default.

There's an xml example on github

I know this question was asked 7 years ago so it probably doesn't matter any more to @Ayrx. Hope it helps to whoever drops by.

2 of 3
5

As long as you're setting the Content-Type header accordingly and respecting the Accept header sent by the client, you're free to return any format you want. You can just have a view that returns your binary data with the application/octet-stream content type.

🌐
ReqBin
reqbin.com › code › python › 6mwlgbqa › python-requests-download-file-example
How do I download a file using Python Requests?
To download a file using the Python ... need to make a GET, POST, or PUT request and read the server's response data using response.content, response.json, or response.raw objects, and then save it to disk using the Python file object methods...
🌐
Stack Overflow
stackoverflow.com › questions › 18937452 › download-files-with-python-rest-url
http - download files with python (REST URL) - Stack Overflow
March 1, 2015 - You can use this python-3 script to download images from http://www.example.org/images/01.jpg to http://www.example.org/images/09.jpg. 2013-09-21T20:53:36.09Z+00:00 ... That code will not work. You commented out the url variable which is not a REST style URL. It will not grab the response to parse out the location. It also doesn't download the file, it reads it.
Find elsewhere
🌐
Safe Community
community.safe.com › home › forums › fme form › integration › fme server rest api python data upload/download
FME Server Rest API Python Data Upload/Download | Community
January 24, 2019 - ... In the current version of FME Server you can use:POST /repositories/< repository >/items/< item >/resources ... Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.
🌐
Narkive
django-rest-framework.narkive.com › NC8rGX1L › rest-api-to-download-file
REST API to download file
' My Code - from rest_framework import viewsets from rest_framework import generics serializer = cdx_compositesSerializer(snippets, many=True) video_file = open('/home/krishna/Downloads/test1.mp4', 'rb') response = HttpResponse(FileWrapper(video_file), content_type= 'application/video', base_name='none') response['Content-Disposition'] = 'attachment; filename="%s"' % 'test1.mp4' return response return Response(serializer.data) Thanks in advance for your help
🌐
Medium
medium.com › @chodvadiyasaurabh › building-a-file-upload-and-download-api-with-python-and-fastapi-3de94e4d1a35
Building a File Upload and Download API with Python and FastAPI | by Saurabh Chodvadiya | Medium
July 30, 2023 - # Inside upload_file function file_path_String = "" for file in files: # ... (Same loop as before) file_path_String = file_path_String + storing_path_in_Database + "," # ... (Rest of the function) # Store the file paths in the database for data_qc_top_10_holding in add_apth.all(): data_qc_top_10_holding.DOCUMENT_PATH = file_path_String db.add(data_qc_top_10_holding) db.commit() response = await getResponse(x_transaction, True, "File Uploaded Successfully") return response · Here, we concatenate the file paths and update the corresponding rows in the database with the file path information. ... @app.post("/download-file") async def download_file( response: Response, request: file_name_schema, header_request: Request, credentials: HTTPAuthorizationCredentials = Security(security), db: Session = Depends(get_db) ): # Function implementation
🌐
CodingTechRoom
codingtechroom.com › question › -download-file-rest-api
How to Download a File Using a REST API - CodingTechRoom
import requests url = "https://api.example.com/file" response = requests.get(url) if response.status_code == 200: with open('downloaded_file', 'wb') as f: f.write(response.content) else: print('Failed to retrieve the file. Status code:', response.status_code) Incorrect API URL or endpoint causing the request to fail. Lack of proper headers such as authentication tokens or content types. Issues with handling API response formats, especially binary or blob data.
🌐
Faculty
docs.faculty.ai › user-guide › apis › flask_apis › flask_file_upload_download.html
More complex APIs: Upload and Download Files with Flask — Faculty platform documentation
import os from flask import Flask, request, abort, jsonify, send_from_directory UPLOAD_DIRECTORY = "/project/api_uploaded_files" if not os.path.exists(UPLOAD_DIRECTORY): os.makedirs(UPLOAD_DIRECTORY) api = Flask(__name__) @api.route("/files") def list_files(): """Endpoint to list files on the server.""" files = [] for filename in os.listdir(UPLOAD_DIRECTORY): path = os.path.join(UPLOAD_DIRECTORY, filename) if os.path.isfile(path): files.append(filename) return jsonify(files) @api.route("/files/<path:path>") def get_file(path): """Download a file.""" return send_from_directory(UPLOAD_DIRECTORY,
🌐
Microsoft Community Hub
techcommunity.microsoft.com › microsoft community hub › communities › products › content management › sharepoint
Download file from SharePoint via API using Python | Microsoft Community Hub
C:\Users\se\PycharmProjects\10135\venv\Scripts\python.exe C:\Users\se\PycharmProjects\10135\sharepoint_file_download.py Traceback (most recent call last): File "C:\Users\se\PycharmProjects\10135\venv\lib\site-packages\office365\runtime\client_request.py", line 38, in execute_query response.raise_for_status() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://xxxx.sharepoint.com/_api/Web
🌐
Epidemiology
epidemiology.tech › home › downloading a csv from rest api using python requests
Downloading a CSV from REST API using Python Requests » Epidemiology and Technology
January 12, 2024 - Then write the Python script: /home/vivek/data_pull/data_pull.py · import requests from requests.models import HTTPBasicAuth from requests import ReadTimeout, ConnectTimeout, Timeout, HTTPError, ConnectionError from time import sleep import os from datetime import datetime import logging import errno import logging.handlers LOG_FILENAME = './logs/Api_Pull.log' # create logger with level = DEBUG logger = logging.getLogger("Api_pull_log") logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=1000000, backupCount=100) fh.setLevel(logging.
🌐
Codementor
codementor.io › community › downloading files from urls in python
Downloading Files from URLs in Python | Codementor
April 17, 2017 - The url-parsing code in conjuction with the above method to get filename from Content-Disposition header will work for most of the cases. Use them and test the results. These are my 2 cents on downloading files using requests in Python.
🌐
OpenText
forums.opentext.com › home › content management (extended ecm) › api, sdk, rest and web services
Facing issue while trying to download file using Rest API - OpenText - Forums
September 17, 2024 - For listing, http://CSurl/otcs/cs.exe/api/v2/nodes/ /nodes where am parsing the json and taking the data id. Then i am giving as input the above received document id to below api http://CSurl/otcs/cs.exe/api/v2/nodes/ /content When ...