403 Forbidden Error when trying to connect to Sharepoint Graph - Client ID & Secret

Running the below code, I receive a 403 forbidden error. Far below is the error. Was wondering why I would be receiving this error. Any help would be greatly appreciated.

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File 



# def get_sharepoint_context_using_user():
 
    # Get sharepoint credentials
# sharepoint_url = 'https://comcastcorp.sharepoint.com'
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File 



# def get_sharepoint_context_using_user():
 
    # Get sharepoint credentials
# sharepoint_url = 'https://comcastcorp.sharepoint.com'

    # # Initialize the client credentials
# user_credentials = UserCredential("abc", "123")

    # # create client context object
# ctx = ClientContext(sharepoint_url).with_credentials(user_credentials)

# web = ctx.web
# ctx.load(web)
# ctx.execute_query()

    # return ctx
	
# get_sharepoint_context_using_user


#Constructing Details For Authenticating SharePoint

client_id = "abc"
client_secret = "123"
site_url = "https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/_api/site/id"

from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext


creds = ClientCredential(client_id, client_secret)
ctx = ClientContext(site_url).with_credentials(creds)
web = ctx.web
ctx.load(web)
ctx.execute_query()

Here is the error:
C:\Work\Programming\sharepointDrive\python>python sharePointUploadTestNewest.py
Traceback (most recent call last):
File “C:\Users\pMalle001\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_request.py”, line 58, in execute_query
response.raise_for_status()
File “C:\Users\pMalle001\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py”, line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/_api/site/id/_api/Web

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “C:\Work\Programming\sharepointDrive\python\sharePointUploadTestNewest.py”, line 47, in
ctx.execute_query()
File “C:\Users\pMalle001\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_runtime_context.py”, line 187, in execute_query
self.pending_request().execute_query(qry)
File “C:\Users\pMalle001\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_request.py”, line 62, in execute_query
raise ClientRequestException(*e.args, response=e.response)
office365.runtime.client_request_exception.ClientRequestException: (‘-2147024891, System.UnauthorizedAccessException’, ‘Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))’, ‘403 Client Error: Forbidden for url: https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/_api/site/id/_api/Web’)

Hi - This is not a Python-related question. You should consult the docs for that website or that URL, or contact Comcast to find out why you cannot access it. Your credentials may be valid for the site in general, but that URL is forbidden - as the error message says.

Hi! If I’m correct, the whole response is stored in the raised exception, might be useful to inspect the response - i.e. body may contain description of what went wrong.

Try something like this:

# these should on the top
import pprint
from office365.runtime.client_request_exception import ClientRequestException

try:
    ctx.execute_query()
except ClientRequestException as e:
    pprint.pprint(e)
    pprint.pprint(dir(e))
    raise

Now I would recommend to utilize the debugger (pdb) to quickly inspect whatever is inspectable, but there are also simpler approaches, like above.

Using a powershell script, I can upload files to the same site at Sign in to your account using client ID & client secret, so I don’t believe it’s a permission issue with the same site with Sign in to your account

I did take your sugesstion, to add the try and raise to debug, and I received the below, which to me seemed more or less the same error

Error was:

  File "C:\Users\pMalle001\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/Documents/_api/Web

Here is the full error:

C:\Work\Programming\sharepointDrive\python>python sharePointUploadTestNewest.py
ClientRequestException(None, None, '404 Client Error: Not Found for url: https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/Documents/_api/Web')
['__cause__',
 '__class__',
 '__context__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getstate__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setstate__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__suppress_context__',
 '__traceback__',
 '__weakref__',
 'add_note',
 'args',
 'characters_written',
 'code',
 'errno',
 'filename',
 'filename2',
 'message',
 'message_lang',
 'payload',
 'request',
 'response',
 'strerror',
 'winerror',
 'with_traceback']
Traceback (most recent call last):
  File "C:\Users\pMalle001\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_request.py", line 58, in execute_query
    response.raise_for_status()
  File "C:\Users\pMalle001\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/Documents/_api/Web

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Work\Programming\sharepointDrive\python\sharePointUploadTestNewest.py", line 52, in <module>
    ctx.execute_query()
  File "C:\Users\pMalle001\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_runtime_context.py", line 187, in execute_query
    self.pending_request().execute_query(qry)
  File "C:\Users\pMalle001\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_request.py", line 62, in execute_query
    raise ClientRequestException(*e.args, response=e.response)
office365.runtime.client_request_exception.ClientRequestException: (None, None, '404 Client Error: Not Found for url: https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/Documents/_api/Web')

Enclosed is the powershell code that does connect fine, and uploads to the sharepoint site fine, using Graph. And, further below, is the python code, trying to connect to the same site, using the same client ID and client secret, that does not. It’s important to note, Graph is what I have permissions for. So, what’s going through my head now does the code that I am using for python not connect to sharepoint with Graph permissions?

Sharepoint code for powershell that does work and does upload to sharepoint fine a file.

#Fill in the appropriate values for the parameters of your Tenant & Selected Site Collection
Param (
    $Tenant = "abc",
    $AppID = "def",
    $SiteID = "ghi",
    $LibraryURL = "https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/Documents",
    $Path = "C:\Work\meGreatTest.txt"
)

 

#COMMENTED OUT ON 10/3/23 $AppCredential = Get-Credential($AppID)
$appID = "def"
$client_secret = "jkl"
 

#region authorize
$Scope = "https://graph.microsoft.com/.default"

 

$Body = @{
    grant_type = "client_credentials"
    client_id = $appID
    client_secret = $client_secret
    scope = "https://graph.microsoft.com/.default"
}

 

$GraphUrl = "https://login.microsoftonline.com/$($tenant)/oauth2/v2.0/token"
$AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
$Access_token = $AuthorizationRequest.Access_token

 

$Header = @{
    Authorization = $AuthorizationRequest.access_token
    "Content-Type"= "application/json"
}
#endregion

 

#region get drives

 

 

$GraphUrl = "https://graph.microsoft.com/v1.0/sites/$SiteID/drives"

 

$BodyJSON = $Body | ConvertTo-Json -Compress
$Result = Invoke-RestMethod -Uri $GraphUrl -Method 'GET' -Headers $Header -ContentType "application/json"
$DriveID = $Result.value| Where-Object {$_.webURL -eq $LibraryURL } | Select-Object id -ExpandProperty id

 

If ($DriveID -eq $null){

 

    Throw "SharePoint Library under $LibraryURL could not be found."
}

 

#endregion

 

#region upload file

 

$FileName = $Path.Split("\")[-1]
$Url  = "https://graph.microsoft.com/v1.0/drives/$DriveID/items/root:/$($FileName):/content"

 

Invoke-RestMethod -Uri $Url -Headers $Header -Method Put -InFile $Path -ContentType 'multipart/form-data' -Verbose
#endregion  

Here is the python code, using the same client ID and client secret that does not work, I believe this time around, it is a new error message - 404 I’m seeing

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File 



# def get_sharepoint_context_using_user():
 
    # Get sharepoint credentials
# sharepoint_url = 'https://comcastcorp.sharepoint.com'
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File 



# def get_sharepoint_context_using_user():
 
    # Get sharepoint credentials
# sharepoint_url = 'https://comcastcorp.sharepoint.com'

    # # Initialize the client credentials
# user_credentials = UserCredential("abc", "123")

    # # create client context object
# ctx = ClientContext(sharepoint_url).with_credentials(user_credentials)

# web = ctx.web
# ctx.load(web)
# ctx.execute_query()

    # return ctx
	
# get_sharepoint_context_using_user


#Constructing Details For Authenticating SharePoint

client_id = "def"
client_secret = "jkl"
#commented out on 10/8/23 site_url = "https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/_api/site/id"
site_url = "https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/Documents"

from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext


creds = ClientCredential(client_id, client_secret)
ctx = ClientContext(site_url).with_credentials(creds)
web = ctx.web
ctx.load(web)
ctx.execute_query()

Here is the updated error message with python

C:\Users\PAULS PC\Desktop\Programming\pythonProgrammingLog\sharepoint>python pythonSharepointForumNew.py
Traceback (most recent call last):
  File "C:\Users\PAULS PC\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_request.py", line 58, in execute_query
    response.raise_for_status()
  File "C:\Users\PAULS PC\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/Documents/_api/Web

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\PAULS PC\Desktop\Programming\pythonProgrammingLog\sharepoint\pythonSharepointForumNew.py", line 52, in <module>
    ctx.execute_query()
  File "C:\Users\PAULS PC\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_runtime_context.py", line 181, in execute_query
    self.pending_request().execute_query(qry)
  File "C:\Users\PAULS PC\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_request.py", line 62, in execute_query
    raise ClientRequestException(*e.args, response=e.response)
office365.runtime.client_request_exception.ClientRequestException: (None, None, '404 Client Error: Not Found for url: https://comcastcorp.sharepoint.com/sites/NEDIV-FIN-COLLECTIONS-COE/Documents/_api/Web')type or paste code here

So, based off what I said, I believe it has to definitely be a python syntax issue perhaps, where another language, powershell works fine. Any help or ideas would be appreciated.