A Step-by-Step Guide to Run the Microsoft Copilot 365 API with Microsoft Graph

What is the best way to run programmatic prompts and responses against Microsoft 365 Copilot? Is it directly from the user? Maybe specific services? Or through a cloud application (Entra ID Enterprise Application)? All answers can be correct as long as they run within a process. Another issue is whether to ask for Microfot 365 Copilot or Copilot Work, or else… And what endpoints are needed? There are many differences between the API endpoints of plugins and API plugins.

The most important thing isn’t to allow users to run direct requests against API endpoints.

This guide will walk you through creating a Copilot 365 API to interact with Microsoft 365 services such as Outlook, OneDrive, and Teams using Entra ID, Microsoft Graph API, and Python. It is designed for MacOS developers who want to automate and interact using Bash and Python.

The article “A Step-by-Step Guide to Run the Microsoft Copilot 365 API with Microsoft Graph from macOS using Bash and Python” provides the fastest way to create an application and work against Microsoft Graph with Copilot-like prompts.

Prerequisites

Before starting, ensure you have the following:

  • Entra ID Application who registered with necessary Microsoft Graph API permissions.
  • Client ID, Client Secret, and Tenant ID from Azure AD.
  • Python 3.x is installed on your MacOS.
  • A working Bash terminal (standard in macOS).

Install Python and Required Libraries

macOS typically comes with Python pre-installed. You will use Python to interact with the Microsoft Graph API. First, verify that you have Python installed:

python3 –version

If Python is not installed, install it using Homebrew:

brew install python

Next, install the required libraries for making HTTP requests, handling OAuth2 authentication, and (optionally) interacting with GPT models if using natural language:

pip3 install requests msal openai

  • requests: To make HTTP requests to Microsoft Graph.
  • msal: Microsoft Authentication Library for managing OAuth2 flows.
  • openai: (Optional) For processing natural language commands using GPT models.

Register an Entra ID Application

To interact with Microsoft 365 services via the API, you must register an application in Entra ID and configure the appropriate permissions.

  1. Register the Entra ID Application:
    • Log in to the Azure portal.
    • Go to Entra ID > App registrations.
    • Click New Registration, name your app (Copilot365API-Testing), and click Register.
  2. Configure API Permissions:
    • After registering the app, go to API Permissions.
    • Click Add a permission > Microsoft Graph.
    • Add the following permissions based on the functionality:
      • Mail.Read: To read user emails.
      • Files.ReadWrite.All: To read/write files in OneDrive.
      • Calendars.ReadWrite: To manage calendar events.
    • After adding permissions, click Grant admin consent.
  3. Create a Client Secret:
    • Under Certificates & secrets, click New Client Secret.
    • Store the secret securely. You will need the Client ID, Client Secret, and Tenant ID for authentication.

Create a Bash Script to Interact with Microsoft 365

Now, you’ll create a bash script that will prompt the user to select an action (fetch emails, calendar events, or OneDrive files) and use Python to handle the corresponding Microsoft Graph API request.

  1. Create a Bash Script: Create a new file and make it executable:touch copilot_365.sh
    chmod +x copilot_365.sh
  2. Edit the Bash Script: Open the script with your preferred editor (nano / vim), and enter the following code:
#!/bin/bash
# Prompt user for action
echo “What would you like to do? Fetch emails, calendar events, or files?”
read user_action
# Prompt for the user email or user ID
echo “Enter the user email or user ID:”
read user_email
# Run Python script based on the user’s action
python3 <<EOF
import requests
from msal import ConfidentialClientApplication
# Azure AD application credentials
CLIENT_ID = ‘0c14d460-e51f-4a0d-b396-977c1dbb399d’
CLIENT_SECRET = ‘5oC8Q~TPVI29W7hAxq1ujd-zJQYVxhjUDjPLyctW’
TENANT_ID = ‘a715de14-3171-4829-a3c3-ed9b566348b8’
# Function to get an access token
def get_access_token():
try:
app = ConfidentialClientApplication(
CLIENT_ID,
authority=AUTHORITY,
client_credential=CLIENT_SECRET
)
token_response = app.acquire_token_for_client(scopes=SCOPE)
if’access_token’in token_response:
print(“Access token successfully acquired.”)
return token_response[‘access_token’]
else:
print(“Error acquiring token:”, token_response.get(‘error_description’, ‘Unknown error’))
returnNone
exceptExceptionas e:
print(f”An exception occurred while getting the access token: {str(e)}”)
returnNone
# Function to fetch emails for a specific user
def fetch_emails(access_token, user_email):
headers = {‘Authorization’: f’Bearer {access_token}’, ‘Content-Type’: ‘application/json’}
url = f’https://graph.microsoft.com/v1.0/users/{user_email}/messages’
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
emails = response.json()
for message in emails[‘value’]:
print(f”From: {message[‘from’][’emailAddress’][‘name’]}, Subject: {message[‘subject’]}”)
else:
print(f”Error fetching emails: {response.status_code} – {response.text}”)
exceptExceptionas e:
print(f”An exception occurred while fetching emails: {str(e)}”)
# Function to fetch calendar events for a specific user
def fetch_calendar_events(access_token, user_email):
headers = {‘Authorization’: f’Bearer {access_token}’, ‘Content-Type’: ‘application/json’}
url = f’https://graph.microsoft.com/v1.0/users/{user_email}/events’
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
events = response.json()
for event in events[‘value’]:
print(f”Event: {event[‘subject’]} on {event[‘start’][‘dateTime’]}”)
else:
print(f”Error fetching calendar events: {response.status_code} – {response.text}”)
exceptExceptionas e:
print(f”An exception occurred while fetching calendar events: {str(e)}”)
# Function to fetch OneDrive files for a specific user
def fetch_files(access_token, user_email):
headers = {‘Authorization’: f’Bearer {access_token}’, ‘Content-Type’: ‘application/json’}
url = f’https://graph.microsoft.com/v1.0/users/{user_email}/drive/root/children’
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
files = response.json()
for file in files[‘value’]:
print(f”File: {file[‘name’]}”)
else:
print(f”Error fetching files: {response.status_code} – {response.text}”)
exceptExceptionas e:
print(f”An exception occurred while fetching files: {str(e)}”)
# Get the access token
access_token = get_access_token()
if access_token:
# Run appropriate function based on user input
if”$user_action” == “emails”:
fetch_emails(access_token, “$user_email”)
elif”$user_action” == “calendar”:
fetch_calendar_events(access_token, “$user_email”)
elif”$user_action” == “files”:
fetch_files(access_token, “$user_email”)
else:
print(“Invalid action. Please choose ’emails’, ‘calendar’, or ‘files’.”)
else:
print(“Failed to retrieve access token. Cannot proceed with the API request.”)
EOF

Note:

Make sure to replace the following parameters

CLIENT_ID = ‘your-client-id’
CLIENT_SECRET = ‘your-client-secret-value’
TENANT_ID = ‘your-tenant-id’
AUTHORITY = f’https://login.microsoftonline.com/{TENANT_ID}’

Run the Bash Script

Once the script is ready, you can run it directly from your terminal:

./copilot_365.sh

The script will prompt you to enter an action (emails, calendar, or files), and the appropriate data will be fetched from your Microsoft 365 account.

Troubleshooting and Tips

401 Unauthorized Error: If you encounter a 401 error, it is likely due to an authentication issue. Ensure that:

  • The Client ID, Client Secret, and Tenant ID are correct.
  • The required API permissions have been granted for the application.
  • An access token is successfully being acquired (check the get_access_token() function for errors).

Solution: Add a debug print in the get_access_token function to display the token response:

token_response = app.acquire_token_for_client(scopes=SCOPE)
print(token_response) # Debugging step
  • Invalid Action Error: If the action is not recognized, ensure that your input exactly matches the options (emails, calendar, files).
  • Permission IssuesEnsure you have added the correct permissions for Microsoft Graph API in the Azure portal and clicked on Grant admin consent.

Make API Calls with Prompt and Response

Once authenticated, you can make requests to Microsoft Graph endpoints and build a prompt-response flow. For example, a user could prompt the API to fetch their latest emails, and the API would return the response.

Here’s a sample Python code for fetching the user’s email:

# Function to call Microsoft Graph API with a prompt-response flow
def fetch_emails(access_token):
# Prompt: Asking user what to fetch
print(“What would you like to do? Fetch emails, calendar events, or files?”)
user_prompt = input(“Type your choice (emails, calendar, files): “).strip().lower()

if user_prompt == ’emails’:
# Fetch the user’s emails
headers = {
‘Authorization’: f’Bearer {access_token}’,
‘Content-Type’: ‘application/json’
}
response = requests.get(‘https://graph.microsoft.com/v1.0/me/messages&#8217;, headers=headers)

if response.status_code == 200:
emails = response.json()
# Response: Display email subjects and senders
for message in emails[‘value’]:
print(f”From: {message[‘from’][’emailAddress’][‘name’]}, Subject: {message[‘subject’]}”)
else:
print(f”Error fetching emails: {response.status_code}”)

elif user_prompt == ‘calendar’:
# Fetch calendar events (you can implement similar logic here)
print(“Fetching calendar events…”)

elif user_prompt == ‘files’:
# Fetch files from OneDrive (you can implement similar logic here)
print(“Fetching files from OneDrive…”)

else:
print(“Invalid input. Please choose emails, calendar, or files.”)

# Execute the function if the token is available
if access_token:
fetch_emails(access_token)

Samples

More samples in the script can be as follows:

# List of random prompts to simulate Copilot-style questions
random_prompts = [
“What meetings do I have tomorrow?”,
“Show me my unread emails.”,
“List the files in my OneDrive.”,
“What tasks do I have due today?”,
“Get the latest emails from a specific sender.”,
“List upcoming events for the next 7 days.”,
“Retrieve files from a specific OneDrive folder.”
]

These samples are Copilot-Like Prompt.

Microsoft 365 Copilot License

No specific Microsoft 365 Copilot license is required for the guide provided, which involves integrating with Microsoft 365 services (Outlook, OneDrive, Calendar) using Microsoft Graph API. And why?

License Considerations

  1. Microsoft Graph API: The Microsoft Graph API is the core service that allows you to interact with various Microsoft 365 services like email, calendar, files, and Teams. Access to the Graph API does not require a Microsoft 365 Copilot license, but it does require that:
    • The user account making API calls must have a Microsoft 365 license (such as Microsoft 365 Business, Office 365, or Enterprise E3/E5, depending on the services you need to access).
    • The Azure AD app you’re using to interact with the API must have the necessary permissions to access those resources, and the user accounts must have the proper licenses for the specific services being used (like OneDrive, Outlook, or Teams).
  2. Microsoft 365 Copilot: Microsoft 365 Copilot is an AI-powered assistant built into Microsoft 365 applications (e.g., Word, Excel, Outlook) to help users with tasks like drafting emails, summarizing documents, and generating reports. The Copilot 365 API guide does not rely on Microsoft’s Copilot AI functionality. Instead, it leverages the Microsoft Graph API and optionally uses OpenAI’s GPT for natural language processing.Therefore, a Microsoft 365 Copilot license is not required unless you’re using Copilot’s integrated AI capabilities within Microsoft Office apps (having Copilot help generate content in Word, summarize emails in Outlook, etc.).
  3. Licenses for Microsoft 365 Users: The users whose data you access via the Microsoft Graph API (e.g., reading emails, accessing OneDrive files) must have a valid Microsoft 365 license. Common licenses include:
    • Microsoft 365 Business Basic, Standard, or Premium: Covers most small and medium business needs.
    • Microsoft 365 Enterprise (E3, E5): These licenses cover larger enterprises and offer additional features such as enhanced security, compliance, and governance.
    • Office 365 licenses: Also provide access to the same services (e.g., Outlook, OneDrive, etc.).

Key Points

  • For API Usage: No Microsoft 365 Copilot license is needed for using Microsoft Graph API. Your focus here is accessing data (like emails, calendar events, and files) from Microsoft 365 services, which requires a Microsoft 365 user license for the relevant services (e.g., Outlook, OneDrive).
  • For Enhanced AI Features: If you’re using OpenAI’s GPT for natural language interaction as described in the guide (optional part for enhancing prompt-response with AI), you’ll need an OpenAI API key but not a Microsoft Copilot license. OpenAI charges for usage based on the API.
  • If Using Microsoft 365 Copilot Features (in Office): If you plan to integrate Microsoft 365 Copilot (the AI assistant built into Office products) directly within your workflows, you’ll need the Microsoft 365 Copilot license associated with the relevant Office 365 apps.

Conclusion

With this guide, you have a fully functional Copilot 365 API running from macOS using Bash and Python. The script lets you interact with Microsoft 365 services like Outlook, OneDrive, and Calendar via Microsoft Graph API. You can extend this guide further by adding features or connecting to other Microsoft 365 services.

Discover more from CYBERDOM

Subscribe now to keep reading and get access to the full archive.

Continue reading