I'm working with bitbucket pipelines to build and upload docker images automatically. We use AWS for our docker repo and they change their login credentials every 12 hours, so we need to retrieve and update the environment variables being used by bitbucket so that it can push the images to aws. I've written the following code using python requests to try to update the environment variables for docker user and password but am getting a "500 Internal Server Error" from bitbucket.
def update_pipeline_variable(uuid, name, value, token):
endpoint = 'https://api.bitbucket.com/2.0/repositories/myuser/myrepo/pipelines_config/variables/{{{variable_uuid}}}?access_token={token}'.format(
variable_uuid=uuid,
token=token
)
body = {
'value': value,
'key': name
}
headers = {"Authorization": "Bearer {token}".format(token=token)}
r = requests.put(endpoint, json=body, headers=headers)
if r.status_code == 200:
print('Successfully updated {variable_name} environment variable.'.format(variable_name=name))
return None
raise RuntimeError('The following error occurred while updating the environment: {error}'.format(error=r.content))
If I remove the access token from the request url and keep it only in the auth header, then I get a 404 instead of a 500. I know the tokens and uuids are valid because I am able to make the request successfully using Postman, so it's something specific to my python implementation. I also tried using the oauth2 requests library with exactly the same results.
Related
When I run this python script on my PC I get the following error: An error occurred: 404
I have created a Wix Store. (Free plan).
While logged into the Wix Store, I have created API.
Account Settings -> API (https://manage.wix.com/account/api-keys)
From the account settings I have the Account ID, and the API Key, with permissions to read, write, delete, update store items.
I have also gone to https://dev.wix.com/ and created an app there.
This created APP provides OAUTH App ID & App Secret Key.
import requests
# Replace YOUR_APP_SECRET and YOUR_STORE_ID with your actual values
# Not sure which set of credentials to put here, since none worked.
app_secret = 'see_post'
store_id = 'see_post'
headers = {
'accept': 'application/json',
'x-wix-app-secret': app_secret
}
response = requests.get(f'https://api.wix.com/stores/{store_id}/products', headers=headers)
if response.status_code == 200:
products = response.json()
print(products)
else:
print('An error occurred:', response.status_code)
Things that confuse me:
Do I need a Wix Developer account, and then create an APP, and install this app on my wix store. (I have already done this, just created an app, named it, nothing else, and installed it, hoping that I could use the app secret key, and my stores site ID, to retrieve the store products.)
Do I use the APP ID & APP Secret Key in my script? Or do I use the Account ID and Account API that I created in the account of the Wix Store.
Is the store id in the URL of the wix dashboard?
https://manage.wix.com/dashboard/23861c7e-333-333-3333-4a18d5f55da2/
What I wish to accomplish, figure out how to make this script run correctly.
Then I will modify it to do the following:
List
Add/remove products
Change Product attributes such as price, description, etc.
Sync Inventory between Wix, and a local database.
Update 1:
I'm now using this code as provided in the API docs.
import json
import requests
headers = {
'Content-Type': 'application/json',
'Authorization': 'token generated by https://dev.wix.com/api/rest/wix-stores/inventory/query-inventory'
}
data = {
"query": {},
"options": {}
}
response = requests.post('https://www.wixapis.com/stores/v2/inventoryItems/query', headers=headers, data=json.dumps(data))
if response.status_code == 200:
inventory_items = response.json()
print(inventory_items)
else:
print('An error occurred:', response.status_code)
However the auth token is only valid for 10 minutes.
a. How can I regenerate this token from my python script?
b. Do I have to use these temp. tokens? Can't I just use the API key?
Looks to me like you're going about this the hard way. I think a much easier approach would be to use http-functions to expose several endpoints that then use the wix-stores-backend API and the wix-data API to access your product data.
import requests
response = requests.get("https://gitlab.com/api/v4/users/ahmed_sh/projects")
print(response.status_code) # 200
print(response.text) # []
print(response.json()) # []
I'm trying to get a list of my GitLab repo projects using python API, but the outputs are nothing! Although, when I use the browser, I got a non-empty response. How can I solve this problem?
This is because you don't have any public projects in your user namespace. If you want to see your private projects in your namespace, you'll need to authenticate with the API by passing a personal access token in the PRIVATE-TOKEN header.
Note, this also won't show projects you work on in other namespaces.
headers = {'PRIVATE-TOKEN': 'Your API key here!'}
resp = requests.get('https://gitlab.com/api/v4/users/ahmed_sh/projects', headers=headers)
print(resp.json())
I'm creating an app that has to show data of an active directory (which is hosted in microsoft azure) i have been told, that this request of data is going to be accomplished by using the Microsoft Graph API through HTTP GET requests.
Apart from “checking” the active directory data in azure, my app has to be capable of read the local accounts’ permissions, so to acomplish that this wouldn’t be possible to be read from the active directory, which means that I will have to check in the computers itself. For that problem, I've been told that I have to do it through powershell programming (to retrieve data of the local accounts).
At the end my application has to run on AWS Lambda.
More than code i would like guys if you can give me an approach of what to use to get to the solution.
What I have done so far:
I created a python file with this code to connect to the microsoft graph API:
There I added a token to access to the graph API, but i couldn't succeed.
I obtained the token from here, that is supposed to be a sample token of microsoft. For now instead of running my app on AWS Lambda, im running it on pycharm.
My Code on python to access to Azure Active Directory:
import http.client, urllib.request, urllib.parse, urllib.error, base64
# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
headers = {
'Authorization': 'Bearer' 'EwAoA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAXu71AU9f4aS4rOK5xoO/SU5HZKSXtCsDe0Pj7uSc5Ug008qTI+a9M1tBeKoTs7tHzhJNSKgk7pm5e8d3oGWXX5shyOG3cKSqgfwuNDnmmPDNDivwmi9kmKqWIC9OQRf8InpYXH7NdUYNwN+jljffvNTewdZz42VPrvqoMH7hSxiG7A1h8leOv4F3Ek/oeJX6U8nnL9nJ5pHLVuPWD0aNnTPTJD8Y4oQTp5zLhDIIfaJCaGcQperULVF7K6yX8MhHxIBwek418rKIp11om0SWBXOYSGOM0rNNN59qNiKwLNK+MPUf7ObcRBN5I5vg8jB7IMoz66jrNmT2uiWCyI8MmYDZgAACPoaZ9REyqke+AE1/x1ZX0w7OamUexKF8YGZiw+cDpT/BP1GsONnwI4a8M7HsBtDgZPRd6/Hfqlq3HE2xLuhYX8bAc1MUr0gP9KuH6HDQNlIV4KaRZWxyRo1wmKHOF5G5wTHrtxg8tnXylMc1PKOtaXIU4JJZ1l4x/7FwhPmg9M86PBPWr5zwUj2CVXC7wWlL/6M89Mlh8yXESMO3AIuAmEMKjqauPrgi9hAdI2oqnLZWCRL9gcHBida1y0DTXQhcwMv1ORrk65VFHtVgYAegrxu3NDoJiDyVaPZxDwTYRGjPII3va8GALAMVy5xou2ikzRvJjW7Gm3XoaqJCTCExN4m5i/Dqc81Gr4uT7OaeypYTUjnwCh7aMhsOTDJehefzjXhlkn//2eik+NivKx/BTJBEdT6MR97Wh/ns/VcK7QTmbjwbU2cwLngT7Ylq+uzhx54R9JMaSLhnw+/nIrcVkG77Hi3neShKeZmnl5DC9PuwIbtNvVge3Q+V0ws2zsL3z7ndz4tTMYFdvR/XbrnbEErTDLWrV6Lc3JHQMs0bYUyTBg5dThwCiuZ1evaT6BlMMLuSCVxdBGzXTBcvGwihFzZbyNoX+52DS5x+RbIEvd6KWOpQ6Ni+1GAawHDdNUiQTQFXRxLSHfc9fh7hE4qcD7PqHGsykYj7A0XqHCjbKKgWSkcAg=='
}
params = urllib.parse.urlencode({
# Specify values for the following required parameters
'api-version': '1.6'})
try:
conn = http.client.HTTPSConnection('graph.windows.net')
# Specify values for path parameters (shown as {...}) and request body if needed
conn.request("GET", "/myorganization/groups/f795caea-121d-49c7-8ae6-a95623add8aa?%s" % params, "", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
This is the error I get after executing my code:
C:\Users\Joan\PycharmProjects\Prueba\venv\Scripts\python.exe C:/Users/Joan/PycharmProjects/Prueba/GraphTest.py
b'{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."},"date":"2018-07-02T21:01:26","requestId":"c3429e83-9cee-4f79-bfa5-642aa8da482a","values":null}}'
Process finished with exit code 0
This section:
headers = {
'Authorization': 'Bearer' 'EwAoA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAXu71AU9f4aS4rOK5xoO/SU5HZKSXtCsDe0Pj7uSc5Ug008qTI+a9M1tBeKoTs7tHzhJNSKgk7pm5e8d3oGWXX5shyOG3cKSqgfwuNDnmmPDNDivwmi9kmKqWIC9OQRf8InpYXH7NdUYNwN+jljffvNTewdZz42VPrvqoMH7hSxiG7A1h8leOv4F3Ek/oeJX6U8nnL9nJ5pHLVuPWD0aNnTPTJD8Y4oQTp5zLhDIIfaJCaGcQperULVF7K6yX8MhHxIBwek418rKIp11om0SWBXOYSGOM0rNNN59qNiKwLNK+MPUf7ObcRBN5I5vg8jB7IMoz66jrNmT2uiWCyI8MmYDZgAACPoaZ9REyqke+AE1/x1ZX0w7OamUexKF8YGZiw+cDpT/BP1GsONnwI4a8M7HsBtDgZPRd6/Hfqlq3HE2xLuhYX8bAc1MUr0gP9KuH6HDQNlIV4KaRZWxyRo1wmKHOF5G5wTHrtxg8tnXylMc1PKOtaXIU4JJZ1l4x/7FwhPmg9M86PBPWr5zwUj2CVXC7wWlL/6M89Mlh8yXESMO3AIuAmEMKjqauPrgi9hAdI2oqnLZWCRL9gcHBida1y0DTXQhcwMv1ORrk65VFHtVgYAegrxu3NDoJiDyVaPZxDwTYRGjPII3va8GALAMVy5xou2ikzRvJjW7Gm3XoaqJCTCExN4m5i/Dqc81Gr4uT7OaeypYTUjnwCh7aMhsOTDJehefzjXhlkn//2eik+NivKx/BTJBEdT6MR97Wh/ns/VcK7QTmbjwbU2cwLngT7Ylq+uzhx54R9JMaSLhnw+/nIrcVkG77Hi3neShKeZmnl5DC9PuwIbtNvVge3Q+V0ws2zsL3z7ndz4tTMYFdvR/XbrnbEErTDLWrV6Lc3JHQMs0bYUyTBg5dThwCiuZ1evaT6BlMMLuSCVxdBGzXTBcvGwihFzZbyNoX+52DS5x+RbIEvd6KWOpQ6Ni+1GAawHDdNUiQTQFXRxLSHfc9fh7hE4qcD7PqHGsykYj7A0XqHCjbKKgWSkcAg=='
}
Requests an additional space between 'Bearer' and the token itself:
headers = {
'Authorization': 'Bearer ' 'EwAoA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAXu71AU9f4aS4rOK5xoO/SU5HZKSXtCsDe0Pj7uSc5Ug008qTI+a9M1tBeKoTs7tHzhJNSKgk7pm5e8d3oGWXX5shyOG3cKSqgfwuNDnmmPDNDivwmi9kmKqWIC9OQRf8InpYXH7NdUYNwN+jljffvNTewdZz42VPrvqoMH7hSxiG7A1h8leOv4F3Ek/oeJX6U8nnL9nJ5pHLVuPWD0aNnTPTJD8Y4oQTp5zLhDIIfaJCaGcQperULVF7K6yX8MhHxIBwek418rKIp11om0SWBXOYSGOM0rNNN59qNiKwLNK+MPUf7ObcRBN5I5vg8jB7IMoz66jrNmT2uiWCyI8MmYDZgAACPoaZ9REyqke+AE1/x1ZX0w7OamUexKF8YGZiw+cDpT/BP1GsONnwI4a8M7HsBtDgZPRd6/Hfqlq3HE2xLuhYX8bAc1MUr0gP9KuH6HDQNlIV4KaRZWxyRo1wmKHOF5G5wTHrtxg8tnXylMc1PKOtaXIU4JJZ1l4x/7FwhPmg9M86PBPWr5zwUj2CVXC7wWlL/6M89Mlh8yXESMO3AIuAmEMKjqauPrgi9hAdI2oqnLZWCRL9gcHBida1y0DTXQhcwMv1ORrk65VFHtVgYAegrxu3NDoJiDyVaPZxDwTYRGjPII3va8GALAMVy5xou2ikzRvJjW7Gm3XoaqJCTCExN4m5i/Dqc81Gr4uT7OaeypYTUjnwCh7aMhsOTDJehefzjXhlkn//2eik+NivKx/BTJBEdT6MR97Wh/ns/VcK7QTmbjwbU2cwLngT7Ylq+uzhx54R9JMaSLhnw+/nIrcVkG77Hi3neShKeZmnl5DC9PuwIbtNvVge3Q+V0ws2zsL3z7ndz4tTMYFdvR/XbrnbEErTDLWrV6Lc3JHQMs0bYUyTBg5dThwCiuZ1evaT6BlMMLuSCVxdBGzXTBcvGwihFzZbyNoX+52DS5x+RbIEvd6KWOpQ6Ni+1GAawHDdNUiQTQFXRxLSHfc9fh7hE4qcD7PqHGsykYj7A0XqHCjbKKgWSkcAg=='
}
I'm assuming this is just some scratch POC code but, just in case, keep in mind that your token will expire after 1hr so hardcoding it like this doesn't make sense. You'll want to fetch a new token as needed and inject it into the header when making the call.
I'm trying to use Streamlabs API. Streamlabs API uses Oauth2 for creating apps. So first I send whoever's using my app to an authorization link containing my app's client id and the scopes I want to use.
(Something like this: streamlabs.com/api/v1.0/authorize?client_id=CLIENT-ID-HERE&redirect_uri=REDIRECT-URI&response_type=code&scope=SOME+SCOPES+HERE)
Once I've done that I receive a code at the redirect uri specified. I then use that code to get the access token for permanent access to the connected user's account. I then receive the access token from a POST request that works perfectly... Now I run into the problem. When getting the temporary code before the access token I specified the scopes: "donations.read +donations.create+alerts.write+alerts.create".
When authorizing, the app asks for permission to the different scopes. The scope in focus is "alerts.write" so that I can send test alerts using POST requests. But this doesn't work for some reason. To send a test alert I have to send a POST request to this url: "https://streamlabs.com/api/alerts/send_test_alert"
I've tried doing that in two different ways.
1:
import requests
url = "https://streamlabs.com/api/alerts/send_test_alert"
data = {
"access_token":"UserAccessTokenHere",
"type":"donation"
}
response = requests.post(url=url, data=data)
print(response.text)
2:
import requests
url = "https://streamlabs.com/api/alerts/send_test_alert?access_token=UserAccessTokenHere&type=donation"
response = requests.post(url=url)
print(response.text)
If I do print(response) it prints "Response [405]".
But if I do print(response.text) I get a long HTML document for this page: Error response page
Any ideas what's going wrong with my Python requests? send_test_alert documentation here: Link
I've contacted support and looks like you've made the same error as me.
You're not actually sending a request to the right URL.
You are a sending a request to: "https://streamlabs.com/api/alerts/send_test_alert"
You should be using the URL: "https://streamlabs.com/api/v1.0/alerts/send_test_alert"
I have been trying to use the Django-REST authentication to validate the user name /password given in a desktop app.
On the server side, I have installed the following DJANGO-REST-FRAMEWORK-JWT package found here:
https://github.com/GetBlimp/django-rest-framework-jwt
I have gone through the example and when I run the following on the command line get a token as a response:
curl -X POST -d "username=luca&password=letmein123" http://localhost:8000/api-token-auth/
And I get:
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InBhbmthaiIsInVzZXJfaWQiOjIsImVtYWlsIjoiIiwiZXhwIjoxNDc5MTE5NzQ2fQ.RA085m-YSnGFheykCCxSVxI_9rW9AC9kEaOkUB5Gm0A"}
I tried something like:
import requests
resp = requests.post('http://127.0.0.1:8000/api-token-auth/', data={}, auth=('luca', 'letmein123'))
However, this always returns response code 400 with Bad request
My question is how can I do that from my desktop python app. I basically want to call the same API with the username and passord and be able to process the response and access protected APIs.
The auth parameter of requests.request is by default meant for Basic/Digest/Custom HTTP Auth, analogous to the -u, --user <user:password> parameter of curl.
You could define your own custom Authentication class to achieve the desired result, but the basic way to achieve the same result as your original curl request is:
resp = requests.post(
'http://localhost:8000/api-token-auth/',
data={"username": "luca", "password": "letmein123"})
The data dictionary can alternatively be supplied as json by using the json parameter if you prefer (the request would be different, but also supported by Django REST framework JWT).
You can then use the token (extracted with token = resp.json()['token']) to access the restricted urls as following:
requests.post(
'http://localhost:8000/some-personal-function/',
json={"foo": 42},
headers={'Authorization': 'JWT ' + token})
By the way looking at response.text might help finding the reason, which would, in the case of your 400 response, contain the following:
'{"username":["This field is required."],"password":["This field is required."]}'