Accessing JWT secured Restful API from python script - python

I can access JWT secured Restful API using curl command as follows
#Get the access Token in a variable ID
export ID=`curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ "password": "admin", "rememberMe": true, "username": "admin" }' 'http://localhost:8080/api/authenticate' | jq -r .id_token`
#Use this token to access endpoint
curl 'http://localhost:8080/api/downloads' --header 'Content-Type: application/json' --header 'Accept: application/json' --header "Authorization: Bearer $ID"
My python script for authentication part and get bearer token is as follows:
import requests
LOGIN_URL = "http://localhost:8080/api/authenticate"
ENDPOINT_URL = 'http://localhost:8080/api/downloads'
PARAMS = {'password': 'admin','rememberMe': True, 'username': 'admin' }
r1 = requests.post(LOGIN_URL, data =PARAMS, headers={"Content-Type": "application/json","Accept": "application/json"})
print(r1)
When i am trying to do the same through python script,Authentication request fails with message <Response [400]>
Help needed !

You are passing a dictionary where you should be passing JSON.
Try using json not data and pass the dictionary:
import requests
LOGIN_URL = "https://httpbin.org/post"
PARAMS = {'password': 'admin','rememberMe': True, 'username': 'admin' }
r1 = requests.post(LOGIN_URL, json=PARAMS, headers={"Content-Type": "application/json","Accept": "application/json"})
print(r1.text)
or pass a string and use data:
import requests
LOGIN_URL = "https://httpbin.org/post"
PARAMS = '{"password": "admin", "rememberMe": true, "username": "admin"}'
r1 = requests.post(LOGIN_URL, data=PARAMS, headers={"Content-Type": "application/json", "Accept": "application/json"})
print(r1.text)

Related

Convert request from curl to python

I have this request using a curl command and I want to translate it to python using the requests library
curl -X POST https://endpoint/prod/api/Translations/start \
-H 'Authorization: Bearer <accessToken>' \
-H 'Content-Type: application/json' \
-d '{ "text": ["first segment to translate.", "second segment to translate."], "sourceLanguageCode": "en", "targetLanguageCode": "de", "model": "general", "useCase": "testing"}'
You can use requests library.
The following curl:
curl -X POST "https://www.magical-website.com/api/v2/token/refresh/" \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"refresh": "$REFRESH_TOKEN"
}'
I wrote in python the following way:
import requests
def get_new_token():
url = 'https://www.magical-website.com/api/v2/token/refresh/'
token = constants.THE_TOKEN
payload = f'{{ "refresh": "{token}" }}'
headers = {"accept": "application/json", "Content-Type": "application/json"}
print("Token handling ....")
r = requests.post(url, data=payload, headers=headers)
print(f"Token status: {r.status_code}")
return r.json()['access']
You can try this one.
import requests
url = "https://endpoint/prod/api/Translations/start"
payload = {
"text": ...,
"sourceLanguageCode": ...,
...
}
headers = { "Authorization": "Bearer ...", "Content-Type": "application/json" }
res = requests.post(url, data = payload, headers = headers)
print(res.status_code)
print(res.text)

Python get data from API using Requests failed

I have been trying to use requests to pull json data with client id and api key, but it won't work.
Here is the info I received from IT:
Request:
curl --location --request GET 'https://api.abc.com/def' \
--header 'clientid: testuser' \
--header 'Accept: application/json' \
--header 'apikey: testapikey1234' \
--header 'dc_session: UUID' \
--header 'dc_transaction_id: UUID'
I wrote the following code in python
import requests
import json
url = 'https://api.abc.com/def'
headers = {'Accept': 'application/json', 'clientid': 'testuser', 'apikey': 'testapikey1234', 'dc_session': 'UUID', 'dc_transaction_id': 'UUID'}
response = requests.get(url, verify = False, headers = headers)
print(response.status_code)
print(response.json())
Unfortunately the code returns 401 status code, with the error message:
{'error': {'type': 'INVALID_CLIENT_IDENTIFIER', 'message': 'Unauthorized. Missing or invalid clientID.'}}
Does anyone have any suggestions?

HTTP Token generation not working in Python requests

So I wrote this script in curl to generate a token
token=$(curl -s -H "Accept: application/json" -H "Content-Type: application/json" --data '{"identifier": "...", "password": "..."}' "$HOST:$PORT/login" | ggrep -Po '"token":"(\K[^"]+)')
which works fine. However with the simplicity of Python 3 I'd like to perform the same task using requests. As I understand running
import requests, json
http = '...'
head = {'accept': 'application/json', 'Content-Type':'application/json'}
data = { 'username' : '...', 'password' : '...' }
r = requests.post(http, data=json.dumps(data), headers=head, verify=False)
print(r.text)
should return the same but I get the error
{"id":"3bca1f46-0577-40a9-8e09-7d68557ad88f","rafalError":"WrongJson","message":"DecodingFailure at .identifier: Attempt to decode value on failed cursor"}
with r.status_code returning 422.

Why does this call work to Postman from Curl but not Python

Curl Code works python does not
trying to change from curl to python
curl --location --request PUT "https://api.getpostman.com/environments/XXXXX-YYYYYY-ZZZZ-BBBB-AAAA-ZZZZZZ?apikey=12334567890" \
--header "Content-Type: application/json" \
--data "{
\"environment\": {
\"values\": [
{\"key\": \"url\", \"value\": \"http://10.12.30.131\"}
]
}
}"
import requests
import json
url = 'https://api.getpostman.com/environments/XXXXX-YYYYYY-ZZZZ-BBBB-AAAA-ZZZZZZ?apikey=12334567890'
header = {"Content-type": "application/json"}
body = '{\"environment\": { \"name\": \"Prod - Deploy\", \"values\": [ {\"key\": \"url\", \"value\": \"http://10.12.30.131\"}]}}'
response = requests.put(url, data=json.dumps(body), headers=header)
print(response.status_code)
print(response.text)
expect a 200 response
the body should be body = '{"environment\": {"name\": "Prod - Deploy\", "values\": [{"key\": "url\", "value\": "http://10.12.30.131\"}, {"key\": "appPath\", "value\": "footytips-apis-v1\"} ]}}'

Insert Calendar using Google API (Python)

I would like to use the Google API to insert a secondary calendar. I've used the Google explanation but can't seem to do it myself. How do you use:
calendar = {
'summary': 'calendarSummary',
'timeZone': 'America/Los_Angeles'
}
created_calendar = service.calendars().insert(body=calendar).execute()
print created_calendar['id']
So if you want to add a secondary calendar this is the curl:
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer here_add_access_token" https://www.googleapis.com/calendar/v3/calendars -d {'summary':'here_calendar_name'}
And in Python is:
import requests
url = "https://www.googleapis.com/calendar/v3/calendars
headers = {
'Content-Type': "application/json",
'Authorization': "Bearer access_token"
}
payload = {
'summary': 'Google Calendar secondary',
}
response = requests.request("POST", url, headers=headers, data=json.dumps(payload))
response = response.text

Categories