Issue
how to do transfer this bash curl in python code.
piece of code what i want remake in python:
response=$(curl -i -H "Content-Type: application/json" "https://api.selvpc.ru/identity/v3/auth/tokens" -d " { \"auth\": { \"identity\": { \"methods\": [\"password\"], \"password\": { \"user\": { \"name\": \"$USER_NAME\", \"domain\": { \"name\": \"$ID_SELECTEL\" }, \"password\": \"$PASSWORD\" } } }, \"scope\": { \"project\": { \"name\": \"$PROJECT_NAME\", \"domain\": { \"name\": \"$ID_SELECTEL\" } } } } }")
what i did:
HEADERS = { \
"Content-type": "application/json"}
PARAMETRES={\
"auth":{\
"identity":{\
"methods":["password"], \
"password":{\
"user":{\
"name" : USER_NAME, \
"domain" : {\
"name":ID_SELECTEL
}, \
"password":PASSWORD
}
}
},\
"scope":{\
"project":{\
"name":PROJECT_NAME, \
"domain":{\
"name":ID_SELECTEL \
}
}
}
}
}
response = requests.get(DATA_URL, params=PARAMETRES, headers=HEADERS)
print(response)
output:
<Response [401]>
I think I might have lost some dictionaries and this is making an error.
(sorry for my bad english)
Solution
Your problem is most likely related to the POST request. The original bash script uses curl -d
, which indicates a POST request, not a GET.
In addition, you pass your parameters as params, which adds them to the URL. Instead, you should pass them in the request body using the json
or data
keyword (depends on what type the server expects - JSON or regular data).
Your rewritten code may look like this:
import requests
import json
HEADERS = {
"Content-Type": "application/json"
}
PARAMETERS = {
"auth": {
"identity": {
"methods": ["password"],
"password": {
"user": {
"name" : USER_NAME,
"domain" : {
"name": ID_SELECTEL
},
"password": PASSWORD
}
}
},
"scope": {
"project": {
"name": PROJECT_NAME,
"domain": {
"name": ID_SELECTEL
}
}
}
}
}
response = requests.post('https://api.selvpc.ru/identity/v3/auth/tokens',
headers=HEADERS,
data=json.dumps(PARAMETERS))
print(response)
Note that the URL for the request is now included in the requests.post
parameters, and not as a DATA_URL
variable. The parameters encoded in JSON are transmitted using the data
keyword.
When working with the API, it is common practice to process response status codes. If you receive a 401, it indicates an authentication problem - your username or password may be incorrect, or the server may require additional authentication that you have not provided.
Answered By - MakarovDs Answer Checked By - Mildred Charles (WPSolving Admin)