Google Places Checkin POST request in Python - python

I'm trying POST a check-in request in Google Places API. The way they described it, I have to request this -
POST https://maps.googleapis.com/maps/api/place/check-in/json?sensor=true_or_false&key=AddYourOwnKeyHere HTTP/1.1
Host: maps.googleapis.com
{
"reference": "place_reference"
}
My Current code looks like this -
def checkin(self, reference="", sensor="true"):
"""
"""
base_url = "https://maps.googleapis.com/maps/api/place/check-in/json"
params = urllib.urlencode(
{
'key': self.API_KEY,
'sensor': sensor,
}
)
post_url = base_url + "?" + params
headers = { 'Host': "maps.googleapis.com" }
data = urllib.urlencode({ 'reference': reference })
req = Request(post_url, data, headers)
response = urllib2.urlopen(req)
resp = response.read()
But I keep getting the error -
urllib2.HTTPError: HTTP Error 400: Bad Request
What am I doing wrong?

Your problem is that the API is expecting JSON when you are sending it the literal reference: xyz
You need to send it the JSON representation.
Try:
data = json.dumps({'reference': reference})

Related

Azure DevOps Python {"count":1,"value":{"Message":"Unexpected character encountered while parsing value: q. Path '', line 0, position 0.\r\n"}}

Trying to get Work Items for an Azure DevOps Project.
import requests
import base64
from azure.devops.connection import Connection
from azure.devops.v5_1.work_item_tracking.models import Wiql
from msrest.authentication import BasicAuthentication
organization = "https://dev.azure.com/dev"
pat = 'ey3nbq'
authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Basic '+authorization
}
payload = {
"query": "SELECT [System.Id] FROM workitemLinks WHERE ([Source].[System.WorkItemType] = 'Task') AND ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Reverse') AND ([Target].[System.WorkItemType] = 'User Story') MODE (DoesNotContain)"
}
response = requests.post(url="https://dev.azure.com/dev/Agile_Board/_apis/wit/wiql?api-version=5.1", headers=headers, data=payload)
print(response.text)
Gives response 400
Have tried many things, been struggling a bit with this. Any help is much appreciated. How to get project's work items without using their ID . Does the request need to be changed in some way?
Update your post to (json=payload):
response = requests.post(url="https://dev.azure.com/YOUR_ORG/Agile_Board/_apis/wit/wiql?api-version=5.1", headers=headers, json=payload)
or use something like this:
payload_str = "{\"query\": \"SELECT [System.Id] FROM workitemLinks WHERE ([Source].[System.WorkItemType] = 'Task') AND ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Reverse') AND ([Target].[System.WorkItemType] = 'User Story') MODE (DoesNotContain)\"}"
response = requests.post(url="https://dev.azure.com/YOUR_ORG/Agile_Board/_apis/wit/wiql?api-version=5.1", headers=headers, data=payload_str)
Check this question: How to POST JSON data with Python Requests?

LinkedIn API request with Python returns "Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields"

I am trying to Retrieve Statistics for Specific UGC Posts using the official documentations
My request looks like this:
requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A00000&ugcPosts[0]=urn%3Ali%3AugcPost%3A111111&ugcPosts[1]=urn%3Ali%3AugcPost%3A222222', headers = headers)
"00000" is the company ID
"111111" and "222222" - are ugcPosts URNs
The headers look like this:
def headers(access_token):
'''
Make the headers to attach to the API call.
'''
headers = {
'Authorization': f'Bearer {access_token}',
'cache-control': 'no-cache',
'X-Restli-Protocol-Version': '2.0.0'
}
I have also passed the scope as one of the parameters, when authorizing:
def authorize(api_url,client_id,client_secret,redirect_uri):
# Request authentication URL
csrf_token = create_CSRF_token()
params = {
'response_type': 'code',
'client_id': client_id,
'redirect_uri': redirect_uri,
'state': csrf_token,
'scope': 'r_liteprofile,r_emailaddress,w_member_social,r_organization_social,r_1st_connections_size,r_ads_reporting,rw_organization_admin,r_basicprofile,r_ads,rw_ads,w_organization_social'
}
response = requests.get(f'{api_url}/authorization',params=params)
Unfortunately this particular request doesn't give me the response I was expecting:
{'serviceErrorCode': 100, 'message': 'Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields [/ugcPosts[1], /ugcPosts[0]]', 'status': 403}
It works ok, when requesting a list of all ugcPosts
requests.get('https://api.linkedin.com/v2/ugcPosts?q=authors&authors=List(urn%3Ali%3Aorganization%3A00000)&sortBy=CREATED&count=100', headers = headers)
I have no clue what am I don't wrong. Can you please help me with my predicament?
The full request code is here
import requests
import json
from liapiauth import auth, headers
def organization_info(headers):
response = requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A00000&ugcPosts[0]=urn%3Ali%3AugcPost%3A1111111&ugcPosts[1]=urn%3Ali%3AugcPost%3A2222222', headers = headers)
organization_info = response.json()
return organization_info
if __name__ == '__main__':
credentials = 'credentials.json'
access_token = auth(credentials)
headers = headers(access_token)
organization_info = organization_info(headers)
with open('lisharelist.json', 'w') as outfile:
json.dump(organization_info, outfile)
So it turns out, that the problem is in request formatting. The documentation is outdated.
The sample request looks like this:
GET https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn:li:organization:2414183&ugcPosts[0]=urn:li:ugcPost:1000000&ugcPosts[1]=urn:li:ugcPost:1000001
Apart from changing ":" to "%3A" we also have to edit the list of ugcPosts. Here is the correct looking sample request:
GET https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A2414183&ugcPosts=List(urn%3Ali%3AugcPost%3A1000000,urn%3Ali%3AugcPost%3A1000001)

Python Requests Returns 400

i have this command
curl -X POST --data-urlencode "payload={\"channel\": \"#test\", \"username\": \"kuhkuh\", \"text\": \"This is posted to #test\", \"icon_emoji\": \":ghost:\"}" https://hooks.slack.com/services/123/123/123
im trying to create it using python so i can use it on my project
import requests
import json
class SlackWrapper:
def __init__(self):
pass
#classmethod
def post_message_to_slack(self, err):
url = 'https://hooks.slack.com/services/123/123/123'
payload = {
'channel' : '#test',
'username' : 'kuhkuh',
'message' : err,
'icon_emoji' : ':ghosts:'
}
try:
alert = requests.post(url, data=payload, headers={'Content-Type': 'application/json'})
print(alert.status_code, ' - ', alert.text, ' - ', json.dumps(payload))
except Exception as e:
print(e)
SlackWrapper.post_message_to_slack("testing error message requests")
the problem is, i keep geting this error
<Response [400]>
where did i went wrong?
Error 400 means "Bad Request", so your payload is wrong.
If your payload is already a dict there is no need to json.dumps it in the json parameter of the post request. Also requests is smart enough to infer the Content-Type, so no need to explicitly set this Header.
#classmethod
def post_message_to_slack(self, err):
url = 'https://hooks.slack.com/services/123/123/123'
# changed the payload
payload = {
"channel": "#test",
"username": "kuhkuh",
"text": "This is posted to #test",
"icon_emoji": ":ghost:"
}
try:
# changed the parameters for posting
alert = requests.post(url, json=payload)
print(alert.status_code, ' - ', alert.text, ' - ', json.dumps(payload))
except Exception as e:
print(e)
You can paste the curl code to postman then get the python code and use that.
For your code the equivalent python code :
import requests
url = "https://hooks.slack.com/services/123/123/123"
payload = 'payload=%7B%22channel%22%3A%20%22%23test%22%2C%20%22username%22%3A%20%22kuhkuh%22%2C%20%22text%22%3A%20%22This%20is%20posted%20to%20%23test%22%2C%20%22icon_emoji%22%3A%20%22%3Aghost%3A%22%7D'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
You are trying to send the data to the server as a dictionary.
Instead try sending it as a json data using requests POST json attribute
payload = {
"channel" = '#test',
"username" = 'kuhkuh',
"message" = err,
"icon_emoji" = ':ghosts:'
}
alert = requests.post(url, json = payload)

Swagger API and interaction with python requests

A product was purchased to enable our users to send/receive SMS over HTTP. Now it's my job to build it into our current CMS platform & database. It's got a swagger API.
Here is the documentation for the specific POST request I am trying to send:
POST: Send an SMS Message
Here is my simple python program to test the functionality. I get a generic 500 internal server error response. What am I doing incorrectly?
import requests
API_URL = "https://api.kenect.com/v1/conversations/messages"
headers = {
'x-api-token': '****************',
'x-api-key': '*******************',
'Content-Type': 'application/json',
}
params = {
'contactPhone': '158572968**',
'locationId': '2045',
'messageBody': 'test sms',
'outgoing': 'true',
}
r=requests.post(url = API_URL, headers = headers, params = params)
print(r)
There seems to be 2 issues:
Content type and payload encoding.
You are using params parameter in the post method. params is used with get method for passing data in the URL's query string.
In the post method, depending on the required content type, you need to use either data parameter to send form-encoded data:
r=requests.post(url = API_URL, headers = headers, data = params)
or json parameter to send application/json payload:
r=requests.post(url = API_URL, headers = headers, json = params)
Remove the 'Content-Type' key from your headers dictionary. data and json parameters will set up correct content type automatically.
outgoing is not a valid request parameter for the /v1/conversations/messages resource. This field is from the response object, not the request one. Remove it from your payload.
So to sum up, for form-encoded payload the code should look like this:
import requests
API_URL = "https://api.kenect.com/v1/conversations/messages"
headers = {
'x-api-token': '****************',
'x-api-key': '*******************',
}
params = {
'contactPhone': '158572968**',
'locationId': '2045',
'messageBody': 'test sms',
}
r=requests.post(url = API_URL, headers = headers, data = params)

"Bad Gateway" error using Python requests module with multipart encoded file POST

I am getting the error message "Bad Gateway
The proxy server received an invalid
response from an upstream server" with the following code:
import requests
url = "https://apis.company.com/v3/media"
attachments = 'media': ('x.mp3', open('x.mp3', 'r'))}
headers = {'content-type': "multipart/form-data",'cache-control': "no-cache"
'Authorization':"Bearer zzz" }
response = requests.post(url, files=attachments, headers = headers)
print response.text
I'm following the example in the requests Quickstart documentation, where it says "You can also pass a list of tuples to the data argument": http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
What is causing this error and how can I fix it?
The main problem was that I set the content-type in the header. This code works:
import requests
url = 'https://apis.company.com/v3/media'
token = 'token-goes-here'
headers = { 'Authorization' : 'Bearer ' + token }
filename = 'x.mp3'
with open(filename, 'rb') as media_file:
attachments = {
'media': (filename, media_file, 'application/octet-stream')
}
response = requests.post(url, files = attachments, headers = headers)
print response.text

Categories

Resources