I created a lambda function to update an incident status on atlassian status page. I think i didnt properly used Patch request. Please guide me, what i am missing.
import json
import urllib3
def lambda_handler(event, context):
# TODO implement
print(event)
message = event['Records'][0]['Sns']['Subject']
print('Subject: ' + message)
if "UP" in message:
print('YO YO')
if "Austria" in message:
API_ENDPOINT = "https://api.statuspage.io/v1/pages/xxxxxx/incidents/xxxxx"
API_KEY = "xxxxxxxxx"
http = urllib3.PoolManager()
PARAMS = {
"incident": {
"name": "Test Incident",
"incident_id": ["xxxxx"],
"status": "resolved",
"body": "issue is Resolved now"
}
}
encoded_payload = json.dumps(PARAMS).encode('utf-8')
HEADERS = {'Authorization': API_KEY}
response = http.request('PATCH', url = API_ENDPOINT, body=encoded_payload, headers=HEADERS)
print(response)
print('Austria update incident')
Related
Trying to understand how it works oauth
How to get authorized user details using Blizzard api?
import json
import requests
client_id = ""
client_secret = ""
region = "eu"
data = {
'grant_type': 'client_credentials'
}
access_token_response = requests.post(f"https://{region}.battle.net/oauth/token", data=data, allow_redirects=False, auth=(client_id, client_secret))
access_token = json.loads(access_token_response.text)["access_token"]
api_call_headers = {
'Authorization': 'Bearer ' + access_token
}
api_call_response = requests.get(f"https://{region}.battle.net/oauth/userinfo", headers=api_call_headers)
I am following documentation to post on my company linkedin page (i am superadministrator) so i used GET https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={your_client_id}&redirect_uri={your_callback_url}&state=foobar&scope=r_liteprofile%20r_emailaddress%20w_member_social to get code then I got access_token using this https://linkedin.com/oauth/v2/accessToken?client_id={client_id}&client_secret={client_Secret}&grant_type=authorization_code&redirect_uri={url}&code={code}
Also i got approved on Marketing program so I dont have any problem at this point but When i try to post using credentials i get nothing in console and nothing appears on my company page.
Here is my code
I have a json with creds gotten from api
{
"client_id": "",
"client_secret": "",
"redirect_uri": "https://www.exampleuri.com",
"access_token": "",
"page_id":"73482979"
}
Then read json
def headers(access_token):
headers = {
'Authorization': f'Bearer {access_token}',
'cache-control': 'no-cache',
'X-Restli-Protocol-Version': '2.0.0'
}
return headers
def auth(credentials):
creds = read_creds(credentials)
#print(creds)
client_id, client_secret = creds['client_id'], creds['client_secret']
redirect_uri = creds['redirect_uri']
api_url = 'https://www.linkedin.com/oauth/v2'
if 'access_token' not in creds.keys():
args = client_id,client_secret,redirect_uri
auth_code = authorize(api_url,*args)
access_token = refresh_token(auth_code,*args)
creds.update({'access_token':access_token})
save_token(credentials,creds)
else:
access_token = creds['access_token']
return access_token
if __name__ == '__main__':
credentials = 'credentials.json'
access_token = auth(credentials)
Finally call functions above
import requests
from linked_credentials import auth,headers
credentials = 'credentials.json'
access_token = auth(credentials)
headers = headers(access_token)
def user_info(headers):
response = requests.get('https://api.linkedin.com/v2/organizations', headers = headers)
user_info = response.json()
return user_info
# Get user id to make a UGC post
user_info = user_info(headers)
urn = user_info['page_id']
api_url = 'https://api.linkedin.com/v2/ugcPosts'
author = f'urn:li:organization:{urn}'
message = '''
Testing post on LinkedIn with python
'''
link = 'https://www.example.com/'
link_text = 'Example!'
post_data = {
"owner": author,
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": message
},
"shareMediaCategory": "ARTICLE",
"media": [
{
"status": "READY",
"description": {
"text": message
},
"originalUrl": link,
"title": {
"text": link_text
}
}
]
}
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "CONNECTIONS"
}
}
if __name__ == '__main__':
r = requests.post(api_url, headers=headers, json=post_data)
r.json()
This is what i have in my app
I'm trying to automate a process in which i have to download some brazilian fund quotes from Anbima (Brazil regulator). I have been able to work around the first steps to retrieve the access token but i don't know how to use the token in order to make requests. Here is the tutorial website https://developers.anbima.com.br/en/como-acessar-nossas-apis/.
I have tried a lot of thing but all i get from the request is 'Could not find a required APP in the request, identified by HEADER client_id.'
If someone could share some light. Thank you in advance.
import requests
import base64
import json
requests.get("https://api.anbima.com.br/feed/fundos/v1/fundos")
ClientID = '2Xy1ey11****'
ClientSecret = 'faStF1Hc****'
codeString = ClientID + ":" + ClientSecret
codeStringBytes = codeString.encode('ascii')
base64CodeBytes = base64.b64encode(codeStringBytes)
base64CodeString = base64CodeBytes.decode('ascii')
url = "https://api.anbima.com.br/oauth/access-token"
headers = {
'content-type': 'application/json'
,'authorization': f'Basic {base64CodeString}'
}
body = {
"grant_type": "client_credentials"
}
r = requests.post(url=url, data=json.dumps(body), headers=headers, allow_redirects=True)
jsonDict = r.json()
##################
urlFundos = "https://api-sandbox.anbima.com.br/feed/precos-indices/v1/titulos-publicos/mercado-secundario-TPF"
token = jsonDict['access_token']
headers2 = {
'content-type': 'application/json'
,'authorization': f'Bearer {token}'
}
r2 = requests.get(url=urlFundos, headers=headers2)
r2.status_code
r2.text
I was having the same problem, but today I could advance. I believe you need to adjust some parameters in the header.
Follows the piece of code I developed.
from bs4 import BeautifulSoup
import requests
PRODUCTION_URL = 'https://api.anbima.com.br'
SANDBOX_URL = 'https://api-sandbox.anbima.com.br'
API_URL = '/feed/fundos/v1/fundos/'
CODIGO_FUNDO = '594733'
PRODUCTION = False
if PRODUCTION:
URL = PRODUCTION_URL
else:
URL = SANDBOX_URL
URL = URL + API_URL + CODIGO_FUNDO
HEADER = {'access_token': 'your token',
'client_id' : 'your client ID'}
html = requests.get(URL, headers=HEADER).content
soup = BeautifulSoup(html, 'html.parser')
print(soup.prettify())
The sandbox API will return a dummy JSON. To access the production API you will need to request access (I'm trying to do this just now).
url = 'https://api.anbima.com.br/oauth/access-token'
http = 'https://api-sandbox.anbima.com.br/feed/precos-indices/v1/titulos-publicos/pu-intradiario'
client_id = "oLRa*******"
client_secret = "6U2nefG*****"
client_credentials = "oLRa*******:6U2nefG*****"
client_credentials = client_credentials.encode('ascii')
senhabytes = base64.b64encode(client_credentials)
senha = base64.b64decode(senhabytes)
print(senhabytes, senha)
body = {
"grant_type": "client_credentials"
}
headers = {
'content-type': 'application/json',
'Authorization': 'Basic b0xSYTJFSUlOMWR*********************'
}
request = requests.post(url, headers=headers, json=body, allow_redirects=True)
informacoes = request.json()
token = informacoes['access_token']
headers2 = {
"content-type": "application/json",
"client_id": f"{client_id}",
"access_token": f"{token}"
}
titulos = requests.get(http, headers=headers2)
titulos = fundos.json()
I used your code as a model, then I've made some changes. I've printed the encode client_id:client_secret and then I've copied and pasted in the headers.
I've changed the data for json.
Good day!
I am trying to use the API of the Kuna.io exchange
There is a method in the documentation: /v3/auth/kuna_codes/redeem
I get the error:
{"messages": ["signature_is_incorrect"]}
Works correctly with other methods
import requests
import time
import hmac
import hashlib
url = "https://api.kuna.io/v3/auth/kuna_codes/redeem"
api_path = "/v3/auth/kuna_codes/redeem"
secret_key = 'key'
public_key = 'key'
nonce = str(int(time.time()*1000.0))
body = str('')
msg = api_path+nonce+body
kun_signature = hmac.new(secret_key.encode('ascii'), msg.encode('ascii'), hashlib.sha384).hexdigest()
payload = {"code": "ZC7Xr-TBcfa-DW3hg-xNUr8-cxnp2-CHada-QT9Yr-L14DZ-5pyjA-UAH-KCode"}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'kun-nonce': nonce,
'kun-apikey': public_key,
'kun-signature': kun_signature,
}
response = requests.request("PUT", url, json=payload, headers=headers)
print(response.text)
My suspicions are that the method is wrong since the signature works correctly with other methods.
The signature should contain a body. Try with this one
payload = {"code": "ZC7Xr-TBcfa-DW3hg-xNUr8-cxnp2-CHada-QT9Yr-L14DZ-5pyjA-UAH-KCode"}
body = json.dumps(payload)
msg = api_path+nonce+body
I prepared this method
def make_bearer_token(token_url):
body = {
"scope": "ingo_dev",
"client_id": "machine__dev",
"client_secret": "0c3b99",
"username": "test.user",
"password": "xxx",
"grant_type": "pass",
}
response = requests.post(token_url, data=body).json()
bearer_token = response["access_token"]
print({'authorization: ' + 'Bearer ' + str(response)})
return bearer_token
I want to pass that bearer_token to another method with string 'authorization':bearer_token
as a header parameter. The method is looking something like that.
#staticmethod
def post_request(endpoint, file, timeout=30):
response = requests.post(endpoint, files=file_dict, timeout=timeout)
return response
A simple solution would be to run your make_bearer_token() from within your post_request method.
Bearer is a header so make a new headers dict with your Authorization header in it, and pass it as a parameter to requests.post()
def post_request(endpoint, file, timeout=30):
headers = {
"Authorization": "Bearer {}".format(make_bearer_token(endpoint))
}
response = requests.post(endpoint, files=file_dict, headers=headers, timeout=timeout)
return response
Edit: Based on your comment below, you might want to make use of class variables
class Uploader:
def __init__(self, url):
self.headers = {
"Authorization": "Bearer {}".format(self.make_bearer_token(url))
}
def post_request(self, endpoint, file, timeout=30):
response = requests.post(endpoint, files=file_dict, headers=self.headers, timeout=timeout)
return response
Usually response access_token don't have prefix bearer. So you try this way.
import requests
bearer_token = response["access_token"]
hed = {'Authorization': 'Bearer ' + bearer_token}
data = {'key' : 'value'}
url = 'https://next.url.com'
response = requests.post(url, json=data, headers=hed)
print(response)
print(response.json())
Please try this. Let me know you feedback on the same.