Hello Bruno Gomes da Silva,
I understand you are trying to create an item in a SharePoint list using Microsoft Graph with app-only authentication and getting a 401 generalException
error. This usually happens when the app doesn't have the correct permissions, or those permissions haven't been approved by an admin.
Initially, I too got same error when I ran your code without granting Application type permission:
Since you're using the client credentials flow, your app needs Application type permission like Sites.ReadWrite.All
with admin consent like this:
After that, run below sample python code that first creates a new item in the list and then lists all items.
import requests
from msal import ConfidentialClientApplication
CLIENT_ID = "appId"
CLIENT_SECRET = "secret"
TENANT_ID = "tenantId"
SHAREPOINT_SITE_ID = "siteId"
LIST_ID = "listId"
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"
SCOPE = ["https://graph.microsoft.com/.default"]
app = ConfidentialClientApplication(
client_id=CLIENT_ID,
authority=AUTHORITY,
client_credential=CLIENT_SECRET
)
token_result = app.acquire_token_for_client(scopes=SCOPE)
if "access_token" not in token_result:
print("Authentication failed:")
print(token_result)
exit(1)
access_token = token_result["access_token"]
headers = {
"Authorization": f"Bearer {access_token}",
"Accept": "application/json",
"Content-Type": "application/json"
}
# Create new list item
create_url = f"https://graph.microsoft.com/v1.0/sites/{SHAREPOINT_SITE_ID}/lists/{LIST_ID}/items"
payload = {
"fields": {
"Title": "Item created with Graph API"
}
}
create_response = requests.post(create_url, headers=headers, json=payload)
print(f"Create Status: {create_response.status_code}")
print("Create Response:", create_response.text)
# List all fields of all items
list_url = f"https://graph.microsoft.com/v1.0/sites/{SHAREPOINT_SITE_ID}/lists/{LIST_ID}/items?expand=fields"
list_response = requests.get(list_url, headers=headers)
print(f"\nList Status: {list_response.status_code}")
if list_response.status_code == 200:
items = list_response.json().get("value", [])
print("Items found:", len(items))
for item in items:
print(f"Item ID: {item['id']}")
for key, value in item.get("fields", {}).items():
print(f" {key}: {value}")
print("------")
else:
print("List Response:", list_response.text)
To confirm that, I checked the same in SharePoint site where item created successfully like this:
Let me know if you still need help with setup or testing. Happy to assist.
Hope this helps!
If this answers your query, do click Accept Answer
and Yes
for was this answer helpful, which may help members with similar questions.
If you have any other questions or are still experiencing issues, feel free to ask in the "comments" section, and I'd be happy to help.