Automatic access to Microsoft's Do API (Graph API) for personal use.

Artem Kleparchuk 0 Reputation points
2024-06-24T13:20:01.3866667+00:00

I am a student and I am creating a Python application for automatic synchronization of Microsoft To Do and Nation Database. The application has already been created and is working, but the Microsoft Graph Api token I received is constantly being updated, and I have to manually enter a new token to make my code work. Please tell me how to access the Microsoft Graph Api without constantly entering a new access_token, autorization_code and other things. Is there any tutorial?

This is my code:

import requests
from msal import ConfidentialClientApplication


def create_confidential_client(client_id, client_secret, authority):
    return ConfidentialClientApplication(
        client_id=client_id,
        client_credential=client_secret,
        authority=authority
    )


def get_access_token(app, scopes):
    auth_url = app.get_authorization_request_url(scopes)
    print(auth_url)
    webbrowser.open(auth_url, new=True)

    authorization_code = input("Enter the authorization code: ")
    token_response = app.acquire_token_by_authorization_code(
        code=authorization_code,
        scopes=scopes
    )
    print(token_response)
    return token_response.get("access_token")



def main():
    client_id = "xxxxxxxxxxxxxxx"
    client_secret = "xxxxxxxxxxxxxxxxxxxxxx"
    authority = "https://login.microsoftonline.com/consumers/"
    scopes = ["Tasks.ReadWrite"]

    app = create_confidential_client(client_id, client_secret, authority)
    access_token = get_access_token(app, scopes)

    print(f"Access_token: {access_token}")

main()

Also i use another code, but repsonse is "{"error":{"code":"BadRequest","message":"/me request is only valid with delegated authentication flow.""

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,184 questions
0 comments No comments
{count} votes