I guess my question is relatively simple and naive, but I'm new to use REST APIs so I would be grateful for any help or hint.
I'm trying to send a request with urllib (or another Python's library that I no need to install).
Based on their guide, The format is:
POST https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
and the JSON request format is:
{
"requests":[
{
"image":{
"content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"
},
"features":[
{
"type":"LABEL_DETECTION",
"maxResults":1
}
]
}
]
}
When I try to send the following text (just for test) in the URL line in my browser:
https://vision.googleapis.com/v1/images:{
"requests":[
{
"image":{
"content":"/9j/7QBEUGhvdG9eYxxxzj/Coa6Bax//Z"
},
"features":[
{
"type":"LABEL_DETECTION",
"maxResults":1
}
]
}
]
}?key=my_api_key
I get unfortunately a 404 error.
What should I do? Should I use any library in order to generate the request? Or should I to place the JSON request in another place in the URL?
If you need to send Request Body with the URL you can use CURL. To test REST API's there is a famous software called POSTMAN. By using this you can send requests and receive the response.
CURL,
curl -v -H "Content-Type: application/json" -X POST \
-d '{"image":{"content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"}, "features":[{"type":"LABEL_DETECTION","maxResults":1}]}' https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
Using POSTMAN you can give these values to it and get results.
Give URL,
https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
Choose HTTP METHOD as,
POST
And add the REQUEST BODY under the raw field and choose JSON(application/json),
{
"requests":[
{
"image":{
"content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"
},
"features":[
{
"type":"LABEL_DETECTION",
"maxResults":1
}
]
}
]
}
This works for me:
import base64
import requests
import json
URL = "https://vision.googleapis.com/v1/images:annotate?key=YOUR_TOKEN"
#image to base64, which is a long long text
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read())
#make api call
def image_request(image_path):
data = {
"requests":[
{
"image":{
"content":encode_image(image_path)
},
"features":[
{
"type":"LABEL_DETECTION", #other options: LABEL_DETECTION FACE_DETECTION LOGO_DETECTION CROP_HINTS WEB_DETECTION
"maxResults": 10
}
]
}
]
}
r = requests.post(URL, json = data)
return r.text
#arg = path of image
def main(argv):
api_answer = json.loads(image_request(argv[1]))
try:
rows = api_answer['responses'][0]['labelAnnotations']
except:
print(file_to_proccess)
print(api_answer)
data = []
for item in rows:
data.append([item['mid'], item['description'], item['score'], item['topicality']])
# save somewhere the data list...
if __name__ == "__main__":
main(sys.argv)
this was tested and work perfect
import base64
import requests
import json
url = "https://vision.googleapis.com/v1/images:annotate"
querystring = {"key":".........."}
headers = {
'Content-Type': "application/json",
}
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read())
def image_request(image_path):
payload = '{ \"requests\":[ { \"image\":{ \"content\":\"'+encode_image(image_path).decode('utf-8')+'" }, \"features\":[ { \"type\":\"TEXT_DETECTION\" } ] } ]}'
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
return response.text
Related
The code snippet is simply about performing a post request to a machine learning model endpoint and logging out the response if successful.
import urllib.request
import json
import os
import ssl
def allowSelfSignedHttps(allowed):
# bypass the server certificate verification on client side
if allowed and not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None):
ssl._create_default_https_context = ssl._create_unverified_context
allowSelfSignedHttps(True) # this line is needed if you use self-signed certificate in your scoring service.
# Request data goes here
# The example below assumes JSON formatting which may be updated
# depending on the format your endpoint expects.
# More information can be found here:
# https://learn.microsoft.com/azure/machine-learning/how-to-deploy-advanced-entry-script
data = {
"Inputs": {
"data": [
{
"test_date": "2000-01-01T00:00:00.000Z",
"cough": false,
"fever": 0,
"sore_throat": false,
"shortness_of_breath": 0,
"head_ache": 0,
"age_60_and_above": "example_value",
"gender": "example_value"
}
]
},
"GlobalParameters": {
"method": "predict"
}
}
body = str.encode(json.dumps(data))
url = 'http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score'
api_key = '' # Replace this with the API key for the web service
# The azureml-model-deployment header will force the request to go to a specific deployment.
# Remove this header to have the request observe the endpoint traffic rules
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
result = response.read()
print(result)
except urllib.error.HTTPError as error:
print("The request failed with status code: " + str(error.code))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())
print(error.read().decode("utf8", 'ignore'))
I have tried this, but I keep getting
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score. (Reason: CORS request did not succeed). Status code: (null)."
function predict() {
axios
.post(
"http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score",
{
Inputs: {
data: [
{
cough: S1Val.value,
fever: S2Val.value,
sore_throat: S3Val.value,
shortness_of_breath: S4Val.value,
head_ache: S5Val.value,
age_60_and_above: a1.value,
gender: a2.value,
},
],
},
GlobalParameters: {
method: "predict",
},
},
{
headers: {
"Access-Control-Allow-Orgin": "*",
"Content-Type": "application/json",
},
}
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
Also note that this endpoint doesn't require any authentication that's why I didn't append an API key to the Bearer when performing the request.
I am attempting to post some data through REST API in Python.
data.json
{
"LastModifiedAt": "2020-12-21T20:19:45.335Z",
...
...
}
I am using following code to POST the data.
with open('data.json') as fh:
data = json.load(fh)
headers = {
'Content-Type': 'application/json',
'X-API-Key':'ABC=='
}
response = requests.post('https://myurl.net/api/v1/resource/int_key/endpoint', headers=headers,data=data)
I always get following as response status_code = 400
{
"ModelState": {
"line": [
"Unexpected character encountered while parsing value: L. Path '', line 0, position 0."
]
},
"Message": "The request is invalid."
}
How do I debug this? My URL is correct according to API documentation. Why does it return "Bad Request" status code?
I replaced data with json and it worked.
response = requests.post('https://myurl.net/api/v1/resource/int_key/endpoint', headers=headers,json=data)
I used Postman as suggested by AndroidDev to debug this.
I was trying to upload single image via Alamofire 5 multipart data, API is working fine on Postman as well as on android side, but it is not working on iOS side.
API is developed in Python flask. Image is taken from camera and by using JPEGCompression uploading image.
Following is my code:
func postMultipartData(imageData: Data, completion:#escaping (Result<AccuracyModel?, ErrorResponse>) -> Void) {
let url = APIConstant.ImageAccuracyBaseUrl.BASEURL
let mimeType = "image/jpeg"
let headers: HTTPHeaders = [
"Content-Type": ContentType.multipart.rawValue
]
AF.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "file", fileName: "file123.jpg", mimeType: mimeType)
print(multipartFormData.boundary)
}, to: url, usingThreshold: UInt64.init(),
method: .post,
headers: headers).response { response in
switch response.result {
case .success(_):
if response.response?.statusCode == 200 || response.response?.statusCode == 201 {
do {
if let data = response.data {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
print(json ?? "")
let decodedData = try! JSONDecoder().decode(AccuracyModel.self, from: data)
DispatchQueue.main.async {
completion(.success(decodedData))
}
} else {
print(response)
}
} catch {
completion(Result.failure(self.generateErroModel()!))
}
} else if response.response?.statusCode == 500 {
completion(Result.failure(self.generateErroModel()!))
} else {
fallthrough
}
break
case .failure(_):
completion(Result.failure(self.generateErroModel()!))
}
}
}
For testing purpose api is using 5000 port, can that be issue?
There are no parameters required, so not sending any.
I have also tried by using NSURLSession, but no luck.
For Flask code, I have referred following link:
https://pytorch.org/tutorials/intermediate/flask_rest_api_tutorial.html
Thanks in Advance.
I would like to use the requests library to make a request to a particular webpage, http://latex2png.com/api/convert, in order to convert some latex to a PNG image. However, I am unsure of what data parameters the website accepts.
Is there any way to use the requests library to see which parameters need to be fulfilled?
I've tried running
options = {
"auth": {"user": "guest", "password": "guest"},
"latex": '$a^3$',
"resolution": 900,
"color": "969696",
}
r = requests.post('http://latex2png.com/api/convert')
print(r.content)
but I get b'{"result-message":"no request","result-code":-2}'.
There is no documentation or help online with this specific API and website.
That's because the way you post is wrong, try this:
import requests
headers = {
"Content-type": "application/x-www-form-urlencoded",
}
data = {
"auth": {
"user": "guest",
"password": "guest"
},
"latex": "a^3",
"resolution": 600,
"color": "969696"
}
r = requests.post('http://latex2png.com/api/convert', headers=headers, json=data) # the right way to send POST requests
print(r.json()) # print the json
image_url = "http://latex2png.com" + r.json()['url']
r = requests.get(image_url)
with open("download.png", "wb+") as f: # download it.
f.write(r.content)
I am working on a api call with python. Here I have the parameters in json format that was generated in the website I am trying to access. But when I try to run the program I get an 415: unsupported Media Type error. Not sure what I am doing wrong, as I am using the parameters generated by the website.
this is my code so far
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
url = 'https://einv-apisandbox.nic.in/gstvital/api/auth'
parameters = {
"header": {
"ClientID": "TheClientIDGoesHere",
"ClientSecret": "TheClientSecretGoesHere"
},
"data": {
"UserName": "Username",
"Password": "Password",
"AppKey": "AppKey",
"ForceRefreshAccessToken": "false"
}
}
response = requests.post(url, params=parameters)
jprint(response.json())
In the above code, I have removed the actual parameters and replaced them with dummy text. But when I try them with the actual parameters I get the following error
{
"status": 415,
"title": "Unsupported Media Type",
"traceId": "|df46105a-49e1b43f80675626.",
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13"
}
One thing I changed was this code "ForceRefreshAccessToken": "false". In the generated json code, the false was not inside quotes
Not sure what I am doing wrong. Please help me.
import requests
import json
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
url = 'https://einv-apisandbox.nic.in/gstvital/api/auth'
parameters = {
"header": {
"ClientID": "TheClientIDGoesHere",
"ClientSecret": "TheClientSecretGoesHere"
},
"data": {
"UserName": "Username",
"Password": "Password",
"AppKey": "AppKey",
"ForceRefreshAccessToken": False
}
}
hdr = {"Content-Type": "application/json"}
response = requests.post(url, data=parameters, headers=hdr)
print(response.status_code)
print(response.json())
Error 415 indicates that the media type is not supported by the site. This can be fixed by explicitly stating in the header that the content-type will be JSON.
hdr = {"Content-Type": "application/json"} The response code from the site is "200:OK", therefore your request works.