Post Request to retrieve bearer token in Python - python

Im having trouble doing a post request call to get the bearer token in Python.
This is my current Python code with the hard coded bearer token.
url = 'https://someURL'
headers = {'Authorization' : 'Bearer <MyToken>'} # I'm hard coding it here from a postman call I'm doing
r = requests.get(url, headers=headers)
#This part prints entire response content in a text like format [{'x':'' ,'y':'', ...etc},{'x':'' ,'y':'', ...etc},...etc]
jsonResponse = r.json()
print("Entire JSON response")
print(jsonResponse)
print("Print each key-value pair from JSON response")
for d in jsonResponse:
for key, value in d.items():
if(key == 'groupId'):
print(key, ":", value)
I've previously been able to do post request in JavaScript like so:
var options = {
method: 'POST',
url: 'https://myurl',
qs:
{
grant_type: 'client_credentials',
scope: 'api',
client_id: 'xyz',
client_secret: '123456abc'
},
headers:
{
'cache-control': 'no-cache',
}
};
How can I get a bearer token post request working in Python?

You can create a simple post request like so and then retrieve the json with response.json() which you were already doing :)
data = {
grant_type: 'client_credentials',
scope: 'api',
client_id: 'xyz',
client_secret: '123456abc'
}
response = requests.post(url, data=data)
jsonResponse = response.json

Related

fetching data from outside API in Django

I have an external API with its Content-Type, Authorization key, and tenant fields. The description of API is like this:
URL: https://url_address.com/
method: POST
Header:
Content-Type: application/json
Authorization: Basic asfvasvGasfssfafssDGDggGDgDSggsdfgsd=
Body: -> raw :
{
"Tenant" : "devED"
}
I try to fetch these data from my django views with this:
headers = {'Content-Type': 'application/json', 'Authorization': 'Basic asfvasvGasfssfafssDGDggGDgDSggsdfgsd='}
Body = { "Tenant": 'devED' }
GetAPI_response = requests.post('https://url_address.com/', headers=headers, params=Body).json()
But it says errors like:
{'Message': 'Request data is in Bad Format.'}
Please suggest how can I fix this?
As of version 2.4.2, requests.post can be passed a json parameter that will be automatically encoded and will set the Content-Type header to application/json meaning you don't have to set it yourself
headers = {'Authorization': 'Basic xxxxxxxxxxxxxx'}
body = {'Tenant': 'devED'}
response = requests.post('https://url_address.com/', headers=headers, json=body)

(Discord api) Change nickname on a server with python requests

I am trying to change the nickname of my account on a website but it's not working. This is the code I used.
import requests
token=input('Enter your token: ')
payload = {
'nick': 'new nickname'
}
headers = {
'authorization': token
}
r = requests.patch('https://discord.com/api/v9/guilds/8652577727676008/members/#me', data=payload, headers=headers)
request method and url | authorization | data
import requests, json
token=input('Enter your token: ')
payload = {
"nick": "tester"
}
headers = {
"Authorization": f"Bot {token}",
"Content-Type": "application/json",
}
r = requests.patch('https://discord.com/api/v9/guilds/8652577727676008/members/#me', data=json.dumps(payload), headers=headers)
print(r.content)
I'm new in apis too. But the mistakes you've made are:
Headers
The authorization should be Bot {token} not just {token} (in case
of bots)
You have not defined the content type
Data
Making the data a json string instead of a dict object worked for me

REST API post request results in successful request but not creation

I've been trying to make a Post Request to my CRM API. The CRM API is very vague:
"You can use POST request when you wish to create records. You POST a JSON encoded string to the servers and it will return a single instance of the record."
POST /{object_name}
Example:
Request URL (POST):
/accounts
Request Body (JSON):
{
"name": "testing API"
}
I've had plenty of success making GET requests regularly, but POST is not working out so easily.
url = "https://apiv4.reallysimplesystems.com/accounts?<KEY>"
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
headers = {
'Content-Type': 'application/json',
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
}
response = requests.post(url, headers=headers, data=payload)
I get a status code 200 when I run this, but I'm really looking for that 201. The only clue that I've got to follow at this point is that when I run:
response.json()
I get the error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I've tried switching the response parameters to json:
response = requests.post(url, headers=headers, json=payload)
I've tried ensuring that my payload is json by using json.dumps():
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
payload = json.dumps(payload)
And I've tried all sorts of other shenanigans that I can't even recall at this point. Does anyone have any idea where I'm going wrong here? The 200 status code makes me feel painfully close.
Replace <AUTH_TOKEN> with your auth token
url = "https://apiv4.reallysimplesystems.com/accounts/"
payload = {"name":"Ziggy"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH_TOKEN>',
}
response = requests.post(url, headers=headers, data=payload)
Problem solved:
import json
import requests
url = "https://apiv4.reallysimplesystems.com/accounts"
payload = {"name":"RSS Test Joe Bloggs","addresscounty/state":"Maryland","source":"Word of Mouth"}
payload = json.dumps(payload)
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH KEY>'
}
response = requests.post(url, headers=headers, data=payload)
Rather than using Postman's code which included the in the URL and used :
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
I replaced it with a standard Authorization header. Secondly, I found that using json.dumps(payload) and json = payload was resulting in a Bad Request.

I am getting an internal server error on my local Python server when authenticating to Yelp API

I am trying to authenticate to the Yelp API and this is what I'm getting:
{ "error": { "description": "client_id or client_secret parameters not found. Make sure to provide client_id and client_secret in the body with the application/x-www-form-urlencoded content-type", "code": "VALIDATION_ERROR" } }
This is the method I have defined in Python and I am have installed Python Flask. I have never worked with an API before this:
#app.route("/run_post")
def run_post():
url = "https://api.yelp.com/oauth2/token"
data = {'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'Content-type': 'application/x-www-form-urlencoded'}
body = requests.post(url, data=json.dumps(data))
return json.dumps(body.json(), indent=4)
The data should be passed as application/x-www-form-urlencoded, so you should not serialize request parameters. You also should not specify Content-Type as parameter, it belongs to request headers.
The final code:
#app.route("/run_post")
def run_post():
url = "https://api.yelp.com/oauth2/token"
data = {'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET}
body = requests.post(url, data=data)
return json.dumps(body.json(), indent=4)
I followed #destiner 's and added the content type to the header and it worked. Here's the resulting code:
#app.route("/run_post")
def run_post():
url = "https://api.yelp.com/oauth2/token"
data = {'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET}
headers = {'Content-type': 'application/x-www-form-urlencoded'}
body = requests.post(url, data=data, headers=headers)
return json.dumps(body.json(), indent=4)

Google Drive API POST requests?

I'm trying to interact with the Google Drive API and while their example is working, I'd like to learn how to make the POST requests in python instead of using their pre-written methods. For example, in python how would I make the post request to insert a file?
Insert a File
How do I add requests and parameters to the body?
Thanks!
UPDATE 1:
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + 'my auth token'}
datax = {'name': 'upload.xlsx', 'parents[]': ['0BymNvEruZwxmWDNKREF1cWhwczQ']}
r = requests.post('https://www.googleapis.com/upload/drive/v3/files/', headers=headers, data=json.dumps(datax))
response = json.loads(r.text)
fileID = response['id']
headers2 = {'Authorization': 'Bearer ' + 'my auth token'}
r2 = requests.patch('https://www.googleapis.com/upload/drive/v3/files/' + fileID + '?uploadType=media', headers=headers2)
To insert a file:
Create a file in Google drive and get its Id in response
Insert a file using Id
Here are the POST parameters for both operations:
URL: 'https://www.googleapis.com/drive/v3/files'
headers: 'Authorization Bearer <Token>'
Content-Type: application/json
body: {
"name": "temp",
"mimeType": "<Mime type of file>"
}
In python you can use "Requests"
import requests
import json
headers = {'Content-Type': 'application/json','Authorization': 'Bearer <Your Oauth token' }
data = {'name': 'testing', 'mimeType': 'application/vnd.google-apps.document'}
r = requests.post(url,headers=headers,data=json.dumps(data))
r.text
Above POST response will give you an id.
To insert in file use PATCH request with following parameters
url: 'https://www.googleapis.com/upload/drive/v3/files/'<ID of file created> '?uploadType=media'
headers: 'Authorization Bearer <Token>'
Content-Type: <Mime type of file created>
body: <Your text input>
I hope you can convert it in python requests.

Categories

Resources