How to post on linkedin company api? - python

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

Related

How to make a Patch request with urllib3?

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')

How to extract data from json response made by an api in python, Django

I am creating a charge and I want from it to take its 'hosted_url' in order to redirect a user from page.
I am trying to extract it from json, but I newbie and don't know how
...
url = "https://api.commerce.coinbase.com/charges"
payload = {
"local_price": {
"amount": 1,
"currency": USDT
},
"name": "Test for fun",
"description": "Project 2",
"pricing_type": "fixed_price"
}
headers = {
"accept": "application/json",
"X-CC-Version": "2018-03-22",
"X-CC-Api-Key" : "**********",
"content-type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
This is a code to make a request to an api in order to create a charge and in JSON Response I get these fields:
{
"data":{
"code": "123DVAS",
"hosted_url": "https://commerce.coinbase.com/charges/123DVAS",
...
}
}
I want somehow to put this message '123DVAS' in variable or to make a redirect like this:
return render(request, 'https://commerce.coinbase.com/charges/123DVAS')
You can do like this:
# Suppose it's your response looks like this
response = {"hosted_url": "https://commerce.coinbase.com/charges/123DVAS"}
id_fecthed = response.get('hosted_url').split('/')[-1]
# You can redner like this
render(request, f'https://commerce.coinbase.com/charges/{id_fecthed}')
# If you sure that always you want to redirect to hosted_url
# Then you can use this
render(request, response.get('hosted_url'))
Edit:
Full code with data read from requests.
import json
response = requests.post(url, json=payload, headers=headers)
data = json.loads(response.text)
hosted_url = data.get("data",{}).get('hosted_url')
if hosted_url:
id_fecthed = hosted_url.split('/')[-1]
return redirect(f'https://commerce.coinbase.com/charges/{id_fecthed}')
else:
print('Host URL not available')

Problem with Post action on Strapi via Python

I'm trying to send a POST and I get this error:
{"data":null,"error":{"status":400,"name":"ValidationError","message":"Missing "data" payload in the request body","details":{}}}
In [ ]:
This is my code:
import requests
import json
myToken = '256e8f598edc0990b39dbfe8c4acf39ec83ee3a1a8f212a7656b3892585755c52857503a356ed003fa6b1f5f4b89fc34b0aa64000bb1bf5bba75257a0128365c75aa96a8cb4ed7a32e7fc7b5ec899ae6d2633a7004ef7f991b8ca6e6bdac4a3a75954425f95cc1a209e09272b5582f58690759f81aecb506070c3c19b3cdac2f'
myUrl = 'http://localhost:1337/api/countries'
head = { 'Authorization': 'Bearer {}'.format(myToken), 'Content-Type': 'application/json'}
session = requests.Session()
session.headers.update(head)
Get request & response (working well):
response = session.get(myUrl)
print (response.text)
{
"data":[
{
"id":1,
"attributes":{
"name":"United States",
"createdAt":"2022-04-09T04:15:13.925Z",
"updatedAt":"2022-04-09T04:15:15.226Z",
"publishedAt":"2022-04-09T04:15:15.220Z"
}
}
],
"meta":{
"pagination":{
"page":1,
"pageSize":25,
"pageCount":1,
"total":1
}
}
}
Post request & response:
data = json.dumps(['data', {'name': 'United States'}])
response = session.post(myUrl, data = data)
print (response.text)
{
"data":null,
"error":{
"status":400,
"name":"ValidationError",
"message":"Missing \"data\" payload in the request body",
"details":{
}
}
}
Thanks in advance
I did the solution for that,
First of all: I changed the "data" to "json"
data = {'data': {'name': 'United states'}}
request = session.post(myUrl, json = data)
print (request.text)

How to get user details after login via oauth?

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)

Can't upload to Team google drive from python

i'm trying to upload a zip file to Team Google Drive, but the file appears in my own Google drive, and not in the Team's folder. I have a permissions for the team's (shared) folder and I can upload files there manually. I'm able to obtain the access_token.This is my code:
import json
import requests
def get_token():
oauth = 'https://www.googleapis.com/oauth2/v4/token' # Google API oauth url
headers = {'content-type': 'application/x-www-form-urlencoded'}
data = {
'grant_type': 'refresh_token',
'client_id': '{CLIENT_ID}',
'client_secret': '{CLIENT_SECRET}',
'refresh_token': '{REFRESH_TOKEN}',
}
token = requests.post(oauth, headers=headers, data=data)
_key = json.loads(token.text)
return _key['access_token']
# Upload files to google drive using access token
def upload_to_drive(files):
token_key = get_token()
headers = {"Authorization": "Bearer " + token_key}
upload = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(upload.text)
if __name__ == '__main__':
file = "my_folder.zip"
para = {
"name": file,
# "parents": [FOLDER_ID],
"parents": [{
"kind": "drive#file",
"driveId": "{TEAM_DRIVE_ID}",
"id": "{FOLDER_ID}",
"supportsAllDrives": True
}],
}
files_for_upload = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': ('application/zip', open("./" + file, "rb"))
}
upload_to_drive(files_for_upload)
Any help is much appreciated!
Find a solution:
import json
import requests
def get_token():
oauth = 'https://www.googleapis.com/oauth2/v4/token' # Google API oauth url
headers = {'content-type': 'application/x-www-form-urlencoded'}
data = {
'grant_type': 'refresh_token',
'client_id': '{CL}',
'client_secret': '{CLIENT_SECRET}',
'refresh_token': '{REFRESH_TOKEN}',
}
token = requests.post(oauth, headers=headers, data=data)
_key = json.loads(token.text)
return _key['access_token']
# Upload files to google drive using access token
def upload_to_drive(files):
token_key = get_token()
headers = {"Authorization": "Bearer " + token_key}
upload = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true",
headers=headers,
files=files
)
print(upload.text)
if __name__ == '__main__':
file = "my_file.zip"
para = {
"name": file,
"parents": ['{FOLDER_ID}'],
}
files_for_upload = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': ('application/zip', open("./" + file, "rb"))
}
upload_to_drive(files_for_upload)
supportsAllDrives should not be a part of metadata!

Categories

Resources