Bing spell check api doesn't work - error code 404 - bing-api

I've followed through the guide written here
https://learn.microsoft.com/en-us/azure/cognitive-services/bing-spell-check/quickstarts/python, but I'm getting a 404 error code. This is the code from the guide:
import requests
import json
api_key = myke
example_text = "Hollo, wrld" # the text to be spell-checked
endpoint = "https://api.cognitive.microsoft.com/bing/v7.0/SpellCheck"
data = {'text': example_text}
params = {
'mkt':'en-us',
'mode':'spell'
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Ocp-Apim-Subscription-Key': api_key,
}
response = requests.post(endpoint, headers=headers, params=params, data=data)
json_response = response.json()
print(json.dumps(json_response, indent=4))
But when I create a resource, the endpoint I get is either https://api.bing.microsoft.com/ or https://spellcheck3.cognitiveservices.azure.com/ depending on the guide.
How do I correctly run this code?

The code as written in the guide doesn't seem to work; here's a solution I found.
search_url = "https://api.bing.microsoft.com/v7.0/spellcheck"
search_term = "wrld helath"
params = {
'mkt':'en-us',
'mode':'spell',
'text' : search_term
}
headers = {"Ocp-Apim-Subscription-Key": subscription_key}
response = requests.get(search_url, headers=headers, params=params)
response.raise_for_status()
search_results = response.json()

Related

Got the error File type is not supported when uploading a file in ruby on rails

url = URI("https://api.podium.com/v4/messages/attachment")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "multipart/form-data"
request["Authorization"] = "Bearer #{access_token}"
form_data = [["attachment",File.open('D:\proj\v5\ap\fl\Screenshot (1).png')],['data', "#{request_data}"]]
request.set_form(form_data, 'multipart/form-data')
response = https.request(request)
response_body = JSON.parse(response.body)
if response.code == '200' || response.code == '201'
return response_body,'success'
else
return response_body,"#{response.message}"
end
rescue Exception => ex
return ex,'Exception'
end
**
When i am sending the request i got the error like
{"code"=>"invalid_request_values", "message"=>"File type is not supported.", "moreInfo"=>"https://docs.podium.com/docs/errors#invalid_request_values"}
**
Here are a couple of things you could try:
The podium documentation says that the images cannot be above 5mb in size. You can verify if this is the case.
https://help.podium.com/hc/en-us/articles/360039896873-Sending-Messages#Attach%20media%20to%20a%20message
I noticed the code snippet you've shared does set have this line as mentioned in their documentation here https://docs.podium.com/reference/messagesend_with_attachment
request["accept"] = 'application/json'
Maybe adding this header might fix it for you, as you are saying that it is working for you in Postman but not in Ruby.
Try uploading the file from the API Doc reference page itself and check out the code sample they provide there. There are some differences in the code sample you've shared, and the one that podium shows in their doc.

Chilkat2-Python - HTTP Form Authentication problem

Trying to convert from python request to chilkat2.HttpRequest :
import requests
data = {"username": "user","password": "pass","remember": "on"}
sign_in_url = 'https://www.tradingview.com/accounts/signin/'
signin_headers = {'Referer': 'https://www.tradingview.com'}
response = requests.post(url=sign_in_url, data=data, headers=signin_headers)
token = response.json()['user']['auth_token']
P.S. Cause no right username and password - will return status_code:200
b'{"error":"Invalid username or password","code":"invalid_credentials"}'
I have this:
http = chilkat2.Http()
req = chilkat2.HttpRequest()
req.AddParam("username","user")
req.AddParam("password","pass")
req.AddParam("remember","on")
req.Path = '/accounts/signin/'
req.HttpVerb = "POST"
http.FollowRedirects = True
http.SendCookies = True
http.SaveCookies = True
http.CookieDir = "memory"
resp = http.SynchronousRequest('www.tradingview.com',443,True,req)
print(http.LastErrorText)
But response - statusCode: 403 Forbidden
What am I doing wrong?
See the tradingview.com API documentation: https://www.tradingview.com/rest-api-spec/#section/Authentication
You can see that an application/x-www-form-urlencoded POST is required.
It's easy to do with Chilkat. See this documentation showing how to send common HTTP request types: https://www.chilkatsoft.com/http_tutorial.asp
You'll want to send a request like this: https://www.chilkatsoft.com/http_post_url_encoded.asp

Ajax PATCH/PUT problem 401 (Unauthorized)

I wrote an API using django and djano-ninja.
Here is my section of api.py file which is imported to URL.
class ORJSONRenderer(BaseRenderer):
media_type = "application/json"
def render(self, request, data, *, response_status):
return orjson.dumps(data)
class ApiKey(APIKeyQuery):
param_name = "api_key"
def authenticate(self, request, key):
try:
return CustomUser.objects.get(api_key=key)
except CustomUser.DoesNotExist:
pass
api_key = ApiKey()
api = NinjaAPI(
title="Good TExt",
version="0.0.1",
description="That This",
renderer=ORJSONRenderer(),
# csrf=True
)
#api.patch(
"/car/color/{new_color}", auth=api_key, tags=["Car"], summary="Does something",
description="Does something"
)
def update_team_name(request, new_color):
try:
#Do something
msg = {"success": "Done"}
except:
msg = {"error": "Problem"}
return HttpResponse(json.dumps(msg), content_type='application/json')
I have other get endpoints too. There is no problem when I request get endpoints.
But when I send a request to patch endpoints I am getting 401 (Unauthorized) only with ajax. I mean python's requests work.
import requests
load = dict(
api_key='SOME HEY'
)
r = requests.get("http://127.0.0.1:8000/api/car/color/red", params=load)
print(r.text)
But javascript doesn't:
$.ajax({
url: "/api/car/color/red",
data: {
"api_key": "some key"
},
cache: false,
type: "PATCH",
success: function(response_country) {
console.log(response_country);
},
error: function(xhr) {
console.log(xhr);
}
});
What I did try
I tried to add:
headers:{"X-CSRFToken": $crf_token},
to header of the ajax request. Even though csrf is set to False in django-ninja
I tried to change from PATCH to PUT
I tried to add a timeout to ajax request
I tried to send the api_key trough header and not the data
with no success.

Google Push notification giving ParseError

I am trying to use google push notification for calendar to be notified if a user's event's start or/and end dateTime changes.
I have followed all the steps from push doc regarding registering and verifying my domain.
My code is as follows:
#blueprint.route("/notifications", methods={'GET','POST'})
def timeBlocker():
email = '....#gmail.com'
user = User.query.filter_by(email=email).first()
thecredentials = {
'client_id': os.getenv('client_id'),
'client_secret':os.getenv('client_secret'),
'refresh_token':user.refresh,
'grant_type': 'refresh_token',
}
req = requests.post(url='https://oauth2.googleapis.com/token', data = thecredentials)
req_ = req.json()
accessToken = req_["access_token"]
print('access token is ' + accessToken)
body = {
'id': '01234567-89ab-cdef-0123456789ab',
'type': 'web_hook',
'address': 'https://dayliii.com/notifications'
}
headers = {'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
}
calendar = '....#group.calendar.google.com'
req = requests.post(url='https://www.googleapis.com/calendar/v3/calendars/....#group.calendar.google.com/events/watch', data = body, headers=headers)
return str(req.json())
Error:
{'error': {'errors': [{'domain': 'global', 'reason': 'parseError', 'message': 'Parse Error'}], 'code': 400, 'message': 'Parse Error'}}
I tried converting from double quotes to single quote as this similar post suggested yet it didn't work.
Lastly, I was curious to know if I should register & verify domain ownership of 'http://localhost:5000/' when working with push notifications in dev mode? As that's the error I am expecting to get that not sure about the way around it.
The data parameter in request() function accepts json format.
You can try converting your body variable into a json string using json.dumps().
Your request code should look like this:
req = requests.post(url='https://www.googleapis.com/calendar/v3/calendars/....#group.calendar.google.com/events/watch', data = json.dumps(body), headers=headers)

Does anyone know how to create a version via Redmine Api Rest?

I want to create a new version for my project via redmine api rest.I folowed the doc on the web https://www.redmine.org/projects/redmine/wiki/Rest_Versions
url = Configuration.redmine+"/projects/#{project_id}/versions"
uri = URI.parse(url)
req = Net::HTTP::Post.new(uri.request_uri)
req.basic_auth(user, pass)
req["Content-Type"] = "application/json"
payload = {
version: {
name:version_name
}
}
req.body = payload.to_json
http = Net::HTTP.new(uri.host, uri.port)
return = response = http.request(req)
the actual result is a HTTPUnprocessableEntity (422) and i expected a 201 created. The response body looks like this:
<div id="content">
<h2>422</h2>
</div>
supposedly the redmine api, when it gives this type of error, in the response body comes the reason of the error but here it shows me nothing

Resources