In Python post request json file 404 - python

It occurred ERROR 404...
I can't understand what is wrong
json file
{"place_name": "대저생태공원", "img_url": "https://encrypted-tbn1.gstatic.com/licensed-image?q=tbn:ANd9GcRRT1TkNZMCkAaZ-tlwXX_XL9UiaDkew5BDsnf4cMMt086OaBhAHlPWGisM-7GOFRwNaXKpGvxhTQZHfwNoyvKRXQ", "score": 4.2, "description": 1679, "address": "부산 강서구 대저1동 2314-11"}
python code
import requests
# Api 호출
url = "https://f053a068dd0ea6.lhrtunnel.link/api/places"
response = requests.post(url= url, data='./j.json')
print(response)
api post code
app.post('/api/add', (req, res) => {
const {place_name, score, description, img_url, address} = req.body;
connection.query(`INSERT INTO place VALUES (0, "${place_name}", ${score}, "${description}", "${img_url}", "${address}");`, (error, rows) => {
if(error) console.log(error);
res.send(rows);
})
})
help me!

You are using the wrong url.
You need to open the file and read the content otherwise you are sending ./j.json instead of the file content
import requests
with open('./j.json') as f :
data = f.read()
# Api 호출
url = "https://f053a068dd0ea6.lhrtunnel.link/api/add"
response = requests.post(url= url, data=data)
print(response)

Related

how to upload reels to facebook with graph api using python

I am trying to upload reel with Graph Api using Python.
I'm getting an error every time I try to upload video.
Error :
{"debug_info":{"retriable":false,"type":"NotAuthorizedError","message":"User not authorized to perform this request"}}
Note: I have given every possible permission to my app and page.
code:
import requests
import os
import json
Title ="Title of the video"
title = Title
description = title
source = f"F:\proj_ytTofb\downloads\{Title}.mp4"
files = {'source': open(source, 'rb')}
file_size = os.path.getsize(source)
print("File Size is :", file_size, "bytes")
def Initialize():
url = f"https://graph.facebook.com/v13.0/{page_id}/video_reels?upload_phase=start"
payload = {
'access_token': token,
}
r = requests.post(url, data = payload)
return r.json()["video_id"]
video_id=Initialize()
print(video_id)
def Upload():
url = f"https://rupload.facebook.com/video-upload/v15.0/{video_id}"
payload ={
'access_token': token,
'offset': 0,
'file_size': file_size,
}
r = requests.post(url, files=files, data=payload)
return r.text
print(Upload())
output: {"debug_info":{"retriable":false,"type":"NotAuthorizedError","message":"User not authorized to perform this request"}}
Your Upload code seem bit wrong if you refer on documentation
def Upload(vidid, size, filedata):
url = f"https://rupload.facebook.com/video-upload/v13.0/{vidid}"
payloadUp = {
'Authorization': 'OAuth ' + page_access_token,
'offset': "0",
'file_size': str(size),
}
print(payloadUp)
r = requests.post(url, data=filedata, headers=payloadUp)
return r.text
with parameter like this
files = {'source': open(mp4_path, 'rb')}
file_size = os.path.getsize(mp4_path)
and then you called it like this
Upload(video_id, file_size, files)
Note: I successfully upload it on fb reels and published it, but I dont what happen the video failed to convert without error notice.

How to write a python loop to change a value for a dictionary key in API request?

I am writing an API request that gives paginated results.
To get results from the next page I need to take a value of 'next_page_cursor' and put it in the parameters of my request that is a dictionary.
This is what I have tried so far. Need to keep changing cursor value in params until there are no more pages.
params = {'title': 'Cybertruck',
'per_page':100,
'cursor': '*'
}
response = requests.get("https://api.aylien.com/news/stories",
headers = headers, params=params).json()
if "next_page_cursor" in response:
cursor = response["next_page_cursor"]
You can use a while loop:
params = {
"title": "Cybertruck",
"per_page": 100,
"cursor": "initial_cursor"
}
def make_request(params)
return requests.get("https://api.aylien.com/news/stories",
headers=headers, params=params).json()
result = []
response = make_request(params)
while "next_page_cursor" in response:
params["cursor"] = response["next_page_cursor"]
response = make_request(params)
result.append(response["information_your_are_interested_in"])

Python Post Request - Getting 415 Error When Sending Files via Outlook API

I've been having some trouble sending files via python's rest module. I can send emails without attachments just fine but as soon as I try and add a files parameter, the call fails and I get a 415 error.
I've looked through the site and found out it was maybe because I wasn't sending the content type of the files when building that array of data so altered it to query the content type with mimetypes; still 415.
This thread: python requests file upload made a couple of more edits but still 415.
The error message says:
"A supported MIME type could not be found that matches the content type of the response. None of the supported type(s)"
Then lists a bunch of json types e.g: "'application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false"
then says:
"matches the content type 'multipart/form-data; boundary=0e5485079df745cf0d07777a88aeb8fd'"
Which of course makes me think I'm still not handling the content type correctly somewhere.
Can anyone see where I'm going wrong in my code?
Thanks!
Here's the function:
def send_email(access_token):
import requests
import json
import pandas as pd
import mimetypes
url = "https://outlook.office.com/api/v2.0/me/sendmail"
headers = {
'Authorization': 'Bearer '+access_token,
}
data = {}
data['Message'] = {
'Subject': "Test",
'Body': {
'ContentType': 'Text',
'Content': 'This is a test'
},
'ToRecipients': [
{
'EmailAddress':{
'Address': 'MY TEST EMAIL ADDRESS'
}
}
]
}
data['SaveToSentItems'] = "true"
json_data = json.dumps(data)
#need to convert the above json_data to dict, otherwise it won't work
json_data = json.loads(json_data)
###ATTACHMENT WORK
file_list = ['test_files/test.xlsx', 'test_files/test.docx']
files = {}
pos = 1
for file in file_list:
x = file.split('/') #seperate file name from file path
files['file'+str(pos)] = ( #give the file a unique name
x[1], #actual filename
open(file,'rb'), #open the file
mimetypes.MimeTypes().guess_type(file)[0] #add in the contents type
)
pos += 1 #increase the naming iteration
#print(files)
r = requests.post(url, headers=headers, json=json_data, files=files)
print("")
print(r)
print("")
print(r.text)
I've figured it out! Took a look at the outlook API documentation and realised I should be adding attachments as encoded lists within the message Json, not within the request.post function. Here's my working example:
import requests
import json
import pandas as pd
import mimetypes
import base64
url = "https://outlook.office.com/api/v2.0/me/sendmail"
headers = {
'Authorization': 'Bearer '+access_token,
}
Attachments = []
file_list = ['test_files/image.png', 'test_files/test.xlsx']
for file in file_list:
x = file.split('/') #file the file path so we can get it's na,e
filename = x[1] #get the filename
content = open(file,'rb') #load the content
#encode the file into bytes then turn those bytes into a string
encoded_string = ''
with open(file, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
encoded_string = encoded_string.decode("utf-8")
#append the file to the attachments list
Attachments.append({
"#odata.type": "#Microsoft.OutlookServices.FileAttachment",
"Name": filename,
"ContentBytes": encoded_string
})
data = {}
data['Message'] = {
'Subject': "Test",
'Body': {
'ContentType': 'Text',
'Content': 'This is a test'
},
'ToRecipients': [
{
'EmailAddress':{
'Address': 'EMAIL_ADDRESS'
}
}
],
"Attachments": Attachments
}
data['SaveToSentItems'] = "true"
json_data = json.dumps(data)
json_data = json.loads(json_data)
r = requests.post(url, headers=headers, json=json_data)
print(r)

Questrade API - Placing Order

Noob questions here but I am trying to place an order using Questrade API. This is my python script so far:
import requests
uri = "https://api01.iq.questrade.com/v1/accounts/<id>/orders"
headers = {'Authorization': 'Bearer <my_bearer>'}
r = requests.post(uri, headers=headers, accountNumber=31455565, symbolId=8049, quantity=10, icebergQuantity=1, limitPrice=10, isAllOrNone=True, isAnonymous=False, timeInForce="GoodTillCanceled", primaryRoute="Auto", secondaryRoute="Auto", orderType="Limit", action="Buy")
response = r.json()
print (response)
This is a sample request from Questrade's webpage:
http://www.questrade.com/api/documentation/rest-operations/order-calls/accounts-id-orders
This is the error I'm getting: TypeError: request() got an unexpected keyword argument 'quantity'
Any help will be highly appreciated. Thankss!
All the parameters of your request (accountNumber, symbolId, quantity, ...) are parameters for Questrade API, not for the post method of request. You need to set them in the body of the request, in json format: http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests
import requests
uri = "https://api01.iq.questrade.com/v1/accounts/<id>/orders"
headers = {'Authorization': 'Bearer <my_bearer>'}
payload = {'accountNumber': 31455565, 'symbolId': 8049, 'quantity': 10, 'icebergQuantity': 1, 'limitPrice': 10, 'isAllOrNone': True, 'isAnonymous': False, 'timeInForce': "GoodTillCanceled", 'primaryRoute': "Auto", 'secondaryRoute': "Auto", 'orderType': "Limit", 'action': "Buy"}
r = requests.post(uri, headers=headers, json=payload)
response = r.json()
print (response)
I created a simple python wrapper to access the questrade API. https://github.com/antoineviscardi/questradeapi
Using it you would get something like this:
import questradeapi as qapi
sess = qapi.Session(<your_bearer>)
sess.post_order(31455565, 8049, 10, 1, 10, None, True, False, "Limit",
"GoodTillCanceled", "Buy", "Auto", "Auto)

python post request json

I need to use Python to do a POST request using JSON format. What I have right now is
url = 'http://mysurl.org'
data = {my data }
headers = {'content-type': 'application/json'}
r = requests.post(url,data= json.dumps(data, headers=headers)
The issue come when my data is not one line but 500 lines of :
[
{
"Id" : "abc123",
"usr": "u1",
"pwd" : "p1"
},
{
"Id" : "abc124",
"usr": "u2",
"pwd" : "p2"
},
{
"Id" : "abc125",
"usr": "u3",
"pwd" : "p3"
}
.......
]
This really threw me off because "Id" field come from a random generater: id = gennum()
usr is from a query: usr = sqlout[0][0], and pwd is from pwd = sqlout[0][1].
I really do not have an idea how to read 500 line of data into my file data=....
I try to use data.append but do not know how to continue after that.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
[update] sorry that question is not specific. my data comes from three different area:
(1) id row come from an random number generator: gennum()
(2) from query my database. sqlout variable will have 500 lines of out put wiht :
user, and pwd. so basically user = sqlout[0][0], and pwd will = sqlout[0][1] and they need to be in the post request body all together, in one request. so when I send the post request, my request bodywill contain 500 entries of json data like stated below. Hope this will clean the question up a little bit.
Read content of the file using open and file.read:
with open('/path/to/json_file') as f:
data = f.read()
url = 'http://mysurl.org'
headers = {'content-type': 'application/json'}
r = requests.post(url, data=data, headers=headers)
UPDATE after reading comments.
You can make dictionaries from multiple data sources using zip and list comprehension:
data = [{'id': id, 'usr': usr, 'pwd': pwd} for id,usr,pwd in
zip(id_data_generator, usr_data_generator, pwd_data_generator)]

Categories

Resources