facebook credentials instead of access token - python

I am new in coding and I am using this code:
import requests
url = (
"https://graph.facebook.com/{album_id}/"
"photos?access_token={access_token}"
).format(
album_id= "ALBUM ID HERE",
access_token= "PUT HERE ACCESS TOKEN" )
files = {'file': open('C:\\Users\\Leonardo\\Desktop\\black_background_texture_86812_1024x1024.jpg', 'rb')}
r = requests.post(url, files=files)
to upload an image from a pc's folder to an album on a facebook page using an access token. How can I do the same thing using facebook credentials and page name instead of access token? I have already tried to look inside facebook SDK documentation and pythonforfacebook documentation but I can't understand how to use codes made for PHP or JAVA or IOS with python. Thanks

Use page_access_token instead of access_token then you can post that image through your page name.

Related

Is there a way to extract credits of a song/track on Spotify?

I was trying to see if I could extract the values of the credit section (Written by, Produced by, etc) off a spotify track.
Using the Spotipy library,I was told there was a function for the same, (track_info['songwriters'] and track_audio_features(trackid)) but they dont work anymore.
Just looking for a solution for the same, irrespective of the library :)
Eg:
In the song "Stormzy - Own It(Feat. Ed Sheeran & Burna Boy)", the credits section is as follows -
Details under 'show Credits' section of the song
I'm trying to retrieve this info through python! :)
This information doesn't seem to be exposed in the spotify API: https://developer.spotify.com
So it seems like there is no way to get this information via a python-package that relies on the official API.
import requests
import json
# Set up the authentication parameters
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"
# Request an access token
response = requests.post("https://accounts.spotify.com/api/token",
data={
"grant_type": "client_credentials"
},
auth=(client_id, client_secret))
# Extract the access token from the response
access_token = json.loads(response.text)["access_token"]
# Set up the headers for the API request
headers = {
"Authorization": f"Bearer {access_token}"
}
# Make the API request
track_id = "3n3Ppam7vgaVa1iaRUc9Lp"
response = requests.get(f"https://api.spotify.com/v1/tracks/{track_id}", headers=headers)
# Print the response
print(response.text)
This code snippet is just an example, you need to replace "YOUR_CLIENT_ID" and "YOUR_CLIENT_SECRET" with the actual values of your Spotify Web API client ID and secret, respectively. Also, this example retrieve the information of a specific track by providing its ID.
Also, You can do more operations like search tracks, artists, albums, etc. in the Spotify Web API by using similar code and different endpoints.
Please make sure you have read and understand the Spotify Web API's terms of use and developer policy before using it in any project.

Azure Websites Kudu REST API - Authentication in Python

I am trying to access the Azure Kudu Web API interface to get historical information about my WebJobs. The URL is https://myfakewebappname.scm.azurewebsites.net/api/triggeredwebjobs/HubSpot/history
This works just fine in a browser with a one time (first time you login) user and password authentication.
When I call it with a python script using the requests library, I get a 401 response code and 'WWW-Authenticate': 'Basic realm="site"'. I then send another request:
resp = requests.get('https://myfakewebappname.scm.azurewebsites.net/api/triggeredwebjobs/HubSpot/history', auth=('actualuser', 'actualpassword')). I use the user and Password that work using my browser.
I get the same 401 response code again with the same response.headers. What am I doing wrong?
The Authentication of the WebJobs Kudu API is via basic auth, to call the API successfully in python, please follow the steps below.
1.Navigate to the Azure portal -> your web app which has the webjob -> click Get publish profile.
2.Open the downloaded file with the format joyweb11.PublishSettings in step 1, note down the userName and userPWD in this file.
3.Then use the code below, replace the value of username and password with the values in step 2, also replace the webapp name in the url with yours, it works fine on my side.
import requests
from base64 import b64encode
username = '$joyweb11'
password = '7pWclexxxxxJlHwoLRwtrneE'
base64AuthInfo = b64encode((username+':'+password).encode('ascii')).decode('ascii')
url = 'https://joyweb11.scm.azurewebsites.net/api/triggeredwebjobs/HubSpot/history'
headers = {'Authorization': 'Basic ' + base64AuthInfo}
response = requests.get(url=url, headers=headers)
print(response.status_code)
print(response.text)

Capturing access token from an API redirect URL

I am trying to capture my access token that is returned by an API during authentication process. The official method of doing the authentication process from the API is:
from xyz_api import accessToken
app_id = "your_app_id"
app_secret = "your_app_secret"
app_session = accessToken.SessionModel(app_id, app_secret)
response = app_session.auth()
The above will return a json like:
{
"code" : 200,
"data" : {
"authorization_code": "some random code"
},
}
Now, the following code is used to generate a URL:
authorization_code = “your_authorization_code”
app_session.set_token(authorization_code)
url = app_session.generate_token()
Now this is where I start having issue.
At this stage, what is recommended by the API author is:
1. Use the generated URL and copy paste it into a browser.
2. The browser will then do the authentication and return the access token to a redirect
url (I used http://localhost:5000).
3. Copy and paste the access token from redirect URL
What I want:
To be able to finish the authentication and get the access_token from
python code itself.
What I tried:
Using requests.get(url), but it doesn't work.
Is there any way to do this all using python only, without having a need to open a browser?
PS: The API I am trying to use is: https://api-docs.fyers.in/v1#authorization
Further Investigation
On further investigation, I discovered the following:
The API uses oauth
The URL obtained from the following code provided by the API author
url = app_session.generate_token()
is same as when I write the following code:
oauth = OAuth2Session('app_id')
authorization_url, state = oauth.authorization_url(url)
The url returned in both cases is of the form:
https://api.fyers.in/api/v1/genrateToken?authorization_code=some_auth_code&appId=my_app_id
If I copy paste this URL in a browser, it send back the access_token to my redirect_url (http://localhost:5000)
I am trying to get the access token using oauth::fetch_token with the following code, which is failing:
oauth1 = OAuth2Session('app_id', state=state, redirect_uri="http://localhost:5000")
token = oauth1.fetch_token('https://api.fyers.in/api/v1/genrateToken/',
client_secret='app_secret',
code='the_auth_code_returned')
Truly appreciate the help.
you are accessing only with Python...
you dont need to do anything manually in a browser..
This API not sure if what you wnat to.
I Believe you registred an APP , got your app_secret
the step
response = app_session.auth()
answer you with a authorization_code
"data" : {
"authorization_code": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqaGdqZzg3NiQ3ODVidjVANjQ3NTZ2NSZnNyM2OTg3Njc5OHhkIjoiWElHVFVYVjBSSSIsImV4cCI6MTU2MTU5NzM5Ny41NjQxNTV9.Agl-Uus63NforrUEdbG7YUlPcbFXu9hLYm4akGuIBkU"
you may access that authorization token like that
import json
r = json.dumps(reponse)
authorization_token = r['data']['authorization_code']
The authorization token AND you app_id must be passed as querystring to https://api.fyers.in/api/v1/genrateToken?
the REAL user will be then asked to accept login trought your app
and if accepted , the user will be redirected to the URL *I imagined you inform in your app register.
let me know if it make sense

How to correctly use PowerBI's REST API?

I have been working on using the powerbi REST API and I haven't been able to properly make use of it. I made use of this and I was able to register an app and get as far as getting an access token, but still I get 401 statuses on my requests.
My major points of confusion are with regards to the app registration:
1) I am trying to read and write data from a python script. Is this a Native-App or a Web Side Server?
2) What is the meaning of the redirect and home urls on the app registration page? I am currently using my localhost:5000 with different /paths. Could this be the source of the issue?
3) My research indicates that there should be some sort of login interaction. I don't have one, is this an indication that something isn't being done properly?
My code is as follows:
import adal
import requests
AUTHORITY_URL = 'https://login.microsoftonline.com/{my_company}.onmicrosoft.com'
RESOURCE = 'https://analysis.windows.net/powerbi/api'
CLIENT_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
CLIENT_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
def make_headers(access_token):
return {
'Authorization': "Bearer {}".format(access_token)
}
context = adal.AuthenticationContext(AUTHORITY_URL)
token = context.acquire_token_with_client_credentials(RESOURCE, CLIENT_ID, CLIENT_SECRET)
access_token = token['accessToken']
headers = make_headers(access_token)
url = "https://api.powerbi.com/v1.0/myorg/datasets"
resp = requests.get(url, headers=headers)
As I said above this works to give me an access token though a get a status 401 response on the request and there is no sign in prompt.
Any help/guidance would be tremendously appreciated.
1) In your case you should register a Native app.
2) Native apps has only Redirect URI. Redirect URI gives AAD more details about the specific application it authenticates. For Native apps you should set it to https://login.live.com/oauth20_desktop.srf.
3) It's hard to say why you are getting Unauthorized response. Check what rights you gave to your application - does it has rights to read or write all datasets? Try to decode the access token at https://jwt.io and look at scp - does it contain "Dataset.Read.All" or "Dataset.ReadWrite.All"?

Python Requests - Azure Graph API Authentication

I am trying to access the Azure AD Graph API using the Python requests library. My steps are to first get the authorization code. Then, using the authorization code, I request an access token/refresh token and then finally query the API.
When I go through the browser, I am able to get my authorization code. I copy that over to get the access token. However, I've been unable to do the same with a Python script. I'm stuck at the part where I get the authorization code.
My script returns a response code of 200, but the response headers don't include that field. I would've expected the new URL with the code to be in the response headers. I would have also expected a response code of 301.
Does anyone know why my response headers don't have the auth code? Also, given the auth code, how would I pull it out to then get the access/refresh tokens using Python?
My code is below:
import requests
s = requests.Session()
s.auth = (USERNAME, PASSWORD)
# Authorize URL
authorize_url = 'https://login.microsoftonline.com/%s/oauth2/authorize' % TENANT_ID
# Token endpoint.
token_url = 'https://login.microsoftonline.com/%s/oauth2/token' % TENANT_ID
payload = { 'response_type': 'code',
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI
}
request = s.get(authorize_url, json=payload, allow_redirects=True)
print request.headers
It looks that you are implementing with Authorization Code Grant Flow via python requests. As the flow shows, the response of the request of authorize_url will redirect to a SSO page of your AD tenant. After your user login on, it will redirect to the location which set in redirect_uri with code as the URL parameters. E.G. http://localhost/?code=AAABAAAAiL...
And your code seems cannot simply display a html page with JavaScript allowed, so it will not redirect to the login on page.
So you can refer to # theadriangreen’s suggestion to implement with a python web server application.
Otherwise, you can refer to Microsoft Azure Active Directory Authentication Library (ADAL) for Python, which is a python package for acquiring access token from AD and can be easily integrated in your python application.

Categories

Resources