Im using postman to call an API. The use case i have is I need to call the api using the Python-Requests and add error handling and e-mail confirmation. The response i get should be written to a file. Im completely new to python and does not have any expertise. Can someone help?
This is the python Requests code i have
import requests
url = "http://XXXX"
payload = {}
headers= {}
response = requests.request("GET", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
You can write it to a file by doing this:
import requests
url = "http://XXXX"
payload = {}
headers= {}
response = requests.request("GET", url, headers=headers, data = payload)
f = open('dir here', 'w')
f.write(response.text.encode('utf8'))
f.close()
import requests
url = "http://XXXX"
payload = {}
headers= {}
response = requests.request("GET", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
file = open("file_location.csv", 'a')
save = f"{response.text.encode('utf8')}"
file.write(save)
file.close()
Related
import requests
import json
# Define the API endpoint and necessary headers and parameters
url = "https://www.googleapis.com/customsearch/v1"
# url = "https://yande.re/post/similar"
api_key = "replace with your api"
headers = {"Content-Type": "image/jpeg"}
params = {"type": "similar", "cx": "d47119ff66e004d6b", "key":api_key}
# Read the image file and convert it to binary
with open("C:\\Users\\Administrator\\Downloads\\theme\\3f559715-f407-47de-8540-1cd9e4fdc56c.jpg", "rb") as f:
image_data = f.read()
# Send the POST request
response = requests.post(url, headers=headers, params=params, data=image_data)
# Check the status code of the response
if response.status_code == 200:
print('ok')
# Parse the JSON response
data = json.loads(response.text)
# Extract the relevant data from the response
similar_images = data["similar_images"]
else:
print(response.status_code)
print('no')
what wrong with my code? My url was wrong? i alway get no when run it
when I try with another URL like https://yande.re/post/similar i get return. what was happen?
https://www.googleapis.com/customsearch/v1 is a GET Request API. But you are trying to do POST method on this API.
Here is the sample of GET Request for this API
url = "https://www.googleapis.com/customsearch/v1?key={API_KEY}&cx={SEARCH_ENGINE_ID}&q={query}&start={start}"
# make the API request
data = requests.get(url).json()
Im trying to mimic this POST request from this site with this payload:
from this URL: https://surviv.io/stats/gert1
Here is an image of the request im trying to mimic.
Here is my current code in python:
import requests
headers = {'content-type': 'application/json; charset=UTF-8'}
url = 'https://surviv.io/api/user_stats'
payload = {"slug":"gert1","interval":"all","mapIdFilter":"-1"}
r = requests.post(url=url, headers=headers, data=payload)
print(r.content)
This returns:
b'<html>\r\n<head><title>500 Internal Server Error</title></head>\r\n<body bgcolor="white">\r\n<center><h1>500 Internal Server Error</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n'
This is not what I want it return. I want it to return the exact response shown in the response tab of the user_stats requests, which contains the player's stats.
This is what I want it to return:
{"slug":"gert1","username":"GERT","player_icon":"","banned":false,"wins":61,"kills":2830,"games":2034,"kpg":"1.4","modes":[{"teamMode":1,"games":1512,"wins":46,"kills":2230,"winPct":"3.0","mostKills":21,"mostDamage":1872,"kpg":"1.5","avgDamage":169,"avgTimeAlive":92},{"teamMode":2,"games":255,"wins":4,"kills":234,"winPct":"1.6","mostKills":8,"mostDamage":861,"kpg":"0.9","avgDamage":162,"avgTimeAlive":102},{"teamMode":4,"games":267,"wins":11,"kills":366,"winPct":"4.1","mostKills":17,"mostDamage":2225,"kpg":"1.4","avgDamage":246,"avgTimeAlive":125}]}
You should use the json attribute rather than data in the post method. r = requests.post(url=url, headers=headers, json=payload)
Change your code to following your forgot to use json :
import json
import requests
headers = {'content-type': 'application/json; charset=UTF-8'}
url = 'https://surviv.io/api/user_stats'
payload = {"slug":"gert1","interval":"all","mapIdFilter":"-1"}
r = requests.post(url=url, headers=headers, data=json.dumps(payload))
print(r.content)
I've run into a problem with Zapier where this code works fine in Python on my computer, but always throws an error in zapier. I'm hoping it is something easy so that I can get this sorted out quickly.
import requests
import base64
response = requests.get('https://prstvod.s3.amazonaws.com/PursuitUP/PUR86083A_AWS.VTT')
response.raise_for_status() # optional but good practice in case the call fails!
output = response.text
#print (output)
output = base64.b64encode(output)
#print (output)
url = "https://api.zype.com/videos/5d5c1b165577de355513e24e/subtitles?api_key=NsaCqjERym-vYTa6OiF97Bk9A1BzM6DHYa3SFS8TXPSR6Q78ChQZskFA0RZ2ZT7C"
headers = {'content-type': 'application/json'}
payload = '{"subtitle":{"language":"English","extension_type":"vtt","file":"'+output+'"}}'
response = requests.request("POST", url, data=payload, headers=headers)
output = response.text
print (output)
I see a couple of things here.
Python Specific
I'm surprised this didn't raise an error on your computer, but b64encode takes a bytes object. The response.text function returns a decode string object.
Zapier Specific
In Zapier, output must be set as a dictionary. The output = response.text line sets it as a string.
Try the following code:
import requests
import base64
response = requests.get('https://prstvod.s3.amazonaws.com/PursuitUP/PUR86083A_AWS.VTT')
response.raise_for_status() # optional but good practice in case the call fails!
output = response.content
#print (output)
output = base64.b64encode(output)
#print (output)
url = "https://api.zype.com/videos/5d5c1b165577de355513e24e/subtitles?api_key=NsaCqjERym-vYTa6OiF97Bk9A1BzM6DHYa3SFS8TXPSR6Q78ChQZskFA0RZ2ZT7C"
headers = {'content-type': 'application/json'}
payload = '{"subtitle":{"language":"English","extension_type":"vtt","file":"'+str(output)+'"}}'
response = requests.request("POST", url, data=payload, headers=headers)
output = {'response': response.text}
print (output)
Tip: You can use the json argument in requests call rather than building your own manually. It would look like:
payload = {"subtitle":{"language":"English","extension_type":"vtt","file":str(output)}}
response = requests.request("POST", url, json=payload, headers=headers)
How can I get respon JSON dictionaries from server with POST:
import json
import requests
url = 'http://apiurl.com'
parameters = {'code':1,
'user': 'username',
'password': 'password'
}
headers = {'content-type': 'application/json'}
response = requests.post(url, data = json.dumps(parameters),headers=headers)
print(response)
output: Response [200]
response = requests.post(url, data=json.dumps(parameters), headers=headers)
print(response)
print(response.text)
Since, you are going to receive a JSON object you can simply use request's built-in JSON decoder Simply do:
j = response.json()
I'm working with wechat APIs ...
here I've to upload an image to wechat's server using this API
http://admin.wechat.com/wiki/index.php?title=Transferring_Multimedia_Files
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=%s&type=image'%access_token
files = {
'file': (filename, open(filepath, 'rb')),
'Content-Type': 'image/jpeg',
'Content-Length': l
}
r = requests.post(url, files=files)
I'm not able to post data
From wechat api doc:
curl -F media=#test.jpg "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"
Translate the command above to python:
import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)
Doc: https://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py
import base64
import json
import requests
api = 'http://localhost:8080/test'
image_file = 'sample_image.png'
with open(image_file, "rb") as f:
im_bytes = f.read()
im_b64 = base64.b64encode(im_bytes).decode("utf8")
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
data = response.json()
print(data)
except requests.exceptions.RequestException:
print(response.text)
server.py
import io
import json
import base64
import logging
import numpy as np
from PIL import Image
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
app.logger.setLevel(logging.DEBUG)
#app.route("/test", methods=['POST'])
def test_method():
# print(request.json)
if not request.json or 'image' not in request.json:
abort(400)
# get the base64 encoded string
im_b64 = request.json['image']
# convert it into bytes
img_bytes = base64.b64decode(im_b64.encode('utf-8'))
# convert bytes data to PIL Image object
img = Image.open(io.BytesIO(img_bytes))
# PIL image object to numpy array
img_arr = np.asarray(img)
print('img shape', img_arr.shape)
# process your img_arr here
# access other keys of json
# print(request.json['other_key'])
result_dict = {'output': 'output_key'}
return result_dict
def run_server_api():
app.run(host='0.0.0.0', port=8080)
if __name__ == "__main__":
run_server_api()
Use this snippet
import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
name_img= os.path.basename(path_img)
files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
with requests.Session() as s:
r = s.post(url,files=files)
print(r.status_code)
I confronted similar issue when I wanted to post image file to a rest API from Python (Not wechat API though). The solution for me was to use 'data' parameter to post the file in binary data instead of 'files'. Requests API reference
data = open('your_image.png','rb').read()
r = requests.post(your_url,data=data)
Hope this works for your case.
import requests
image_file_descriptor = open('test.jpg', 'rb')
# Requests makes it simple to upload Multipart-encoded files
files = {'media': image_file_descriptor}
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()
Don't forget to close the descriptor, it prevents bugs: Is explicitly closing files important?
For Rest API to upload images from host to host:
import urllib2
import requests
api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'
img_file = urllib2.urlopen(image_url)
response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)
You can use option verify set to False to omit SSL verification for HTTPS requests.
This works for me.
import requests
url = "https://example.com"
payload={}
files=[
('file',('myfile.jpg',open('/path/to/myfile.jpg','rb'),'image/jpeg'))
]
response = requests.request("POST", url, auth=("my_username","my_password"), data=payload, files=files)
print(response.text)
If you have CURL then you can directly get request from Postman.
import requests
url = "your URL"
payload={}
files=[
('upload_file',('20220212235319_1509.jpg',open('/20220212235319_1509.jpg','rb'),'image/jpeg'))
]
headers = {
'Accept-Language': 'en-US',
'Authorization': 'Bearer yourToken'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)