fetching data from outside API in Django - python

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)

Related

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.

Post Request to retrieve bearer token in 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

passing header in post method to access token

I am trying to pass header in post method for generating access token. however I am getting the wrror about invalid syntax. my header code is as below
headers=("Authorization: Basic RXadsdsdsdsdsdsdsdsdjkfhsuidhsuihf==","Content-Type: application/x-www-form-urlencoded")
headers=('Authorization': 'Basic RXadsdsdsdsdsdsdsdsdjkfhsuidhsuihf==','Content-Type': 'application/x-www-form-urlencoded')
Assuming that you are using Requests, headers should be a dictionary, so:
headers={
"Authorization": "Basic RXadsdsdsdsdsdsdsdsdjkfhsuidhsuihf==",
"Content-Type": "application/x-www-form-urlencoded"
}
You can try the below code:
auth_token = "Basic {}".format(token)
headers = {'Content-Type': 'application/json', 'Authorization': auth_token}

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.

Python Request Post with param data

This is the raw request for an API call:
POST http://192.168.3.45:8080/api/v2/event/log?sessionKey=b299d17b896417a7b18f46544d40adb734240cc2&format=json HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json
Content-Length: 86
Host: 192.168.3.45:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
{"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
This request returns a success (2xx) response.
Now I am trying to post this request using requests:
import requests
headers = {'content-type' : 'application/json'}
data ={"eventType" : "AAS_PORTAL_START",
"data" : {"uid": "hfe3hf45huf33545",
"aid": "1",
"vid": "1"}
}
url = ("http://192.168.3.45:8080/api/v2/event/log?"
"sessionKey=9ebbd0b25760557393a43064a92bae539d962103&"
"format=xml&"
"platformId=1")
requests.post(url, params=data, headers=headers)
The response from this request is
<Response [400]>
Everything looks fine to me and I am not quite sure what I posting wrong to get a 400 response.
params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.
Your raw post contains JSON data though. requests can handle JSON encoding for you, and it'll set the correct Content-Type header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument.
You could split out the URL parameters as well:
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
then post your data with:
import requests
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, json=data)
The json keyword is new in requests version 2.4.2; if you still have to use an older version, encode the JSON manually using the json module and post the encoded result as the data key; you will have to explicitly set the Content-Type header in that case:
import requests
import json
headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, data=json.dumps(data), headers=headers)
Assign the response to a value and test the attributes of it. These should tell you something useful.
response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
status_code should just reconfirm the code you were given before, of course
Set data to this:
data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}

Categories

Resources