Converting cURL to Python: With extra parameters - python

I am trying to make API requests with proper authorization. I looked at Conversion of curl to python Requests but am having trouble putting the authorization headers.
This is what I have so far:
import base64
import http.client
import requests
import json
headers = {
"Content-Type": "application/json",
'Authorization': 'Basic %s' % base64.b64encode(b'username:password').decode('ascii'),
}
payload = {json.dumps({"one":["two:three:four"]})}
url = 'https://website/v1'
r = requests.post(url, data=payload, headers=headers)
if __name__=='__main__':
print (r.text)
The only difference between the link provided above and my code is that he has query={"tags":["test1","test2"]} I do not have that at all.
This is the curl I am trying to translate to get what I got above.
curl -X POST -u "username:password" -H "Content-Type:application/json" "https://website.com" -d '{"ids":["something:numberOne:numbertwo"]}'
Any help appreciated.

Related

Python access to API- Authentication Error

I've have been accessing an supportpal API via curl just fine using the following command. (https://docs.supportpal.com/current/REST+API)
curl.exe -i -u 'APIKEY:x' -X GET https://support.url.org/api/user/user/3697
This correctly grabs the data. I've trying replicate this with python but i continually have issues with authentication and get the following error.
Failed to authenticate because of bad credentials or an invalid authorization header
The code i'm using is straight forward.
import requests
import json
url = "https://support.url.org/api/user/user/3697"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer: {APIKEY:x}"
}
response = requests.request("GET", url, headers=headers)
print(response. Text)
I'm thinking i have an issue with the auth header, but can't figure it out.
from requests.auth import HTTPBasicAuth
import requests
url = 'https://support.url.org/api/user/user/3697'
headers = {'Accept': 'application/json'}
auth = HTTPBasicAuth('apikey', x)
req = requests.get(url, headers=headers, auth=auth)

Curl command works fine, while Python requests returns 404

Curl
curl "https://api.wanikani.com/v2/summary" \ -H "Wanikani-Revision: 20170710" \ -H "Authorization: Bearer <API-KEY>"
This command returns the expected json.
Python code
import requests
headers = {"Wanikani-Revision": "20170710", "Authorization": "Bearer <API-KEY>"}
res = requests.post('https://api.wanikani.com/v2/summary', headers = headers)
print(res.text)
This code returs 404.
{"error":"Not found","code":404}
That function only accepts GET. Look https://docs.api.wanikani.com/20170710/#summary
Try:
import requests
headers = {"Wanikani-Revision": "20170710", "Authorization": "Bearer <API-KEY>"}
res = requests.get('https://api.wanikani.com/v2/summary', headers = headers)
print(res.text)

Convert CURL API command to Python API using requests and json

I am connecting through an API to receive data. From the website API documentation, the instructions use either two CURL methods to connect the API; however, I need to connect using python.
1st Method
Curl Example
curl -d '' -X POST 'https://api.bcda.cms.gov/auth/token' \
-H "accept: application/json" \
-H "authorization: Basic <Client_Secret>"
My Python Conversion:
import requests
import json
url = 'https://api.bcda.cms.gov/auth/token'
headers = {"accept": "application/json", "authorization": 'Basic',
'<API_Key>': '<API_Secret>'}
r = requests.post(url = url, data ={}, headers = headers)
print(r)
2nd Method Curl
curl -d '' -X POST 'https://api.bcda.cms.gov/auth/token' \
--user <Client_Key>:<Client_Secret> \
-H "accept: application/json"
My 2nd Python conversion code:
import requests
import json
url = 'https://api.bcda.cms.gov/auth/token'
user = {"<Client_Key>":"<Client_Secret>", "accept": "application/json"}
r = requests.post(url = url, headers = user)
print(r)
I am receiving a 403 connection error, meaning "response status code indicates that the server understands the request but refuses to authorize it."
You should use auth parameter and not headers to convert --user option
headers = {'accept': 'application/json'}
r = requests.post(url=url, headers=headers, auth=(client_key, client_secret))

Python - post request fails when using requests

When using the shell, I can successfully create a new user by running
curl --user administrator:pasword "Content-Type: application/json" https://localhost:8080/midpoint/ws/rest/users -d #user.json
However when I try to do the same thing in python using requests, I get a 200 response and no user is created.
This is the script I am using:
import requests
headers = {
'Content-Type': 'application/json',
}
data = open('user.json')
response = requests.post('https://localhost:8080/midpoint/ws/rest/users', headers=headers, data=data, auth=('Administrator', 'password'))
print(response)
To me they look the same. What is different in the python request that is stopping the user from being created?
I compare the post date with curl and python requests.And i found the difference.
CURL: {"user" : "hero","pd":30}
Requests: pd=30&user=hero
Then this is my test.
import requests
import json
headers = {
'Content-Type': 'application/json',
}
with open('user.json') as j:
data = json.load(j)
response = requests.post('http://127.0.0.1:8080',
headers=headers,
json = data,
auth=('Administrator', 'password'))
print(response.headers)
I think using json = data would work as well, but I was finally successful using json dumps: data=json.dumps(data)

I am calling a Rest API Curl command using python, But the post request is not working

So here is my curl command, In command line, curl script is working fine
curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" -u user:password URL -d '{"key1":"value1","key2":"value2"}'
Now I have converted my code to python and the code look like this :
import requests
import json
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
data = '{"key1":"value1","key2":"value2"}'
requests.post('URL', headers=headers, data=data, auth=('user', 'password'))
When I ran this code, I am not getting any output.
Please let me know what I am doing wrong in here.
At first, the 'url' parameter in requests.post should be an complete url including the 'http://' or 'https://'.
Secondly, if you need to post some data in form of application/json, using Python protogenic dict will be fine. like this
data = {"key1":"value1","key2":"value2"}
you might be looking at something like this?
r = requests.post("http://{}/Command?".format(web_addr), params=dict)
print r.text
In Python 3.6.1, you should get the response 200 message if the following code gets executed, with a existing 'URL':
from requests import post
data = {"key1":"value1","key2":"value2"}
print(post('URL', json=data))

Categories

Resources