cURL to python Requests: form with file attachment - python

I have the following cURL request which works successfully:
curl https://daDomain.com/v2-beta/media \
--header "Authorization: Bearer TOKEN" \
--form media=#recording.mp3 \
--form 'configuration={"configuration":{"keywords":{"groups":["data"]}}}'
Below is the python-requests version of the code, which when called returns a 400 error saying a "mediaUrl is not a valid URL".
import requests
headers = {}
headers["Authorization"] = "Bearer TOKEN"
url = "https://daDomain.com/v2-beta/media"
configuration = '{"configuration":{"keywords":{"groups":["data"]}}}'
filepath = 'recording.mp3'
files = {'media' : open('filepath.mp3', 'rb'), 'configuration' : configuration}
r = requests.post(url, headers = headers, files=files)

Related

Curl command works fine, while Python requests returns 404

Curl
curl "https://api.wanikani.com/v2/summary" \ -H "Wanikani-Revision: 20170710" \ -H "Authorization: Bearer <API-KEY>"
This command returns the expected json.
Python code
import requests
headers = {"Wanikani-Revision": "20170710", "Authorization": "Bearer <API-KEY>"}
res = requests.post('https://api.wanikani.com/v2/summary', headers = headers)
print(res.text)
This code returs 404.
{"error":"Not found","code":404}
That function only accepts GET. Look https://docs.api.wanikani.com/20170710/#summary
Try:
import requests
headers = {"Wanikani-Revision": "20170710", "Authorization": "Bearer <API-KEY>"}
res = requests.get('https://api.wanikani.com/v2/summary', headers = headers)
print(res.text)

Convert CURL API command to Python API using requests and json

I am connecting through an API to receive data. From the website API documentation, the instructions use either two CURL methods to connect the API; however, I need to connect using python.
1st Method
Curl Example
curl -d '' -X POST 'https://api.bcda.cms.gov/auth/token' \
-H "accept: application/json" \
-H "authorization: Basic <Client_Secret>"
My Python Conversion:
import requests
import json
url = 'https://api.bcda.cms.gov/auth/token'
headers = {"accept": "application/json", "authorization": 'Basic',
'<API_Key>': '<API_Secret>'}
r = requests.post(url = url, data ={}, headers = headers)
print(r)
2nd Method Curl
curl -d '' -X POST 'https://api.bcda.cms.gov/auth/token' \
--user <Client_Key>:<Client_Secret> \
-H "accept: application/json"
My 2nd Python conversion code:
import requests
import json
url = 'https://api.bcda.cms.gov/auth/token'
user = {"<Client_Key>":"<Client_Secret>", "accept": "application/json"}
r = requests.post(url = url, headers = user)
print(r)
I am receiving a 403 connection error, meaning "response status code indicates that the server understands the request but refuses to authorize it."
You should use auth parameter and not headers to convert --user option
headers = {'accept': 'application/json'}
r = requests.post(url=url, headers=headers, auth=(client_key, client_secret))

Save m4a file after using authorization header to download

I am trying to download the m4a file of a recorded Zoom meeting from Zoom cloud. Here is the Zoom documentation on completed recording webhooks I am referencing. Specifically, I am trying to implement the section where Zoom describes the download_token in its schema explanation.
This is what I have so far:
from flask import Flask, request
import sys
import pprint
pp = pprint.PrettyPrinter(indent=2)
import requests
app = Flask(__name__)
#app.route('/notification/', methods = ['GET', 'POST'])
def notification():
if request.method == 'POST':
content = request.json
# pp.pprint(content)
if content['event'] == 'recording.completed':
process_recording(content['download_token'], content['payload']['object']['recording_files'])
return 'This should be where the webhook sends info to'
def process_recording(download_token, recordings_list):
recording = next(
(recording for recording in recordings_list if recording["recording_type"] == 'audio_only'),
None)
url = recording['download_url']
headers = {
'content-type': 'application/json',
'authorization': 'Bearer ' + download_token + ' --header content-type:'
}
response = requests.get(url, headers=headers)
if response:
print('Success!')
else:
print('An error has occurred.')
Am I converting the curl command correctly? The curl command should be in this format:
curl --request GET \
--url (download_url) \
--header 'authorization: Bearer (download_token) \
--header 'content-type: application/json'
Furthermore, how do I save the m4a file? What exactly does my response variable store?
Your header is wrong...
compare...
headers = {
'content-type': 'application/json',
'authorization': 'Bearer ' + download_token + ' --header content-type:'
}
with
--header 'authorization: Bearer (download_token) \
--header 'content-type: application/json'
The value for the authorization header should be
"Bearer (%s)" % download_token
or
f"Bearer ({download_token})"
if you use Python 3.6 or higher.

convert curl get to rest api to python

I have this curl command:
curl -X GET --header 'Accept: application/vnd.pagerduty+json;version=2' --header 'Authorization: Token token=y_NbAkKc66ryYTWUXYEu' 'https://api.pagerduty.com/services?time_zone=UTC&sort_by=name'
I need to convert it to python using requests library
import requests
def support(self):
services_list = requests.get('I need to convert the link to pass it here as a parameter')
import requests
def support():
headers = {
'Accept': 'application/vnd.pagerduty+json;version=2',
'Authorization': 'Token token=y_NbAkKc66ryYTWUXYEu'}
payloads = (
('time_zone', 'UTC'),
('sort_by', 'name'),)
services_list = requests.get('https://api.pagerduty.com/services', headers=headers, params=payloads)

Curl request to python request

I have a curl request as below:
curl -X POST \
https://example.com \
-H 'Content-Type: multipart/form-data' \
--form-string 'message=<messageML>Hello world!</messageML>'
How do i pass --form-string data in python request?
Thanks!
Use the files parameter to post your data, example:
import requests
url = 'https://httpbin.org/anything'
data = {'message':'<messageML>Hello world!</messageML>'}
r = requests.post(url, files=data)
print(r.text)
You don't have to use headers because 'multipart/form-data' is the default 'Content-Type' header when posting files.

Categories

Resources