Microsoft Graph API
This page is imported automatically from an external repository.
Source project: Open repository
This Module is used for handling the communication with the Microsoft Graph API
Get Started
Depending on the Use case different Permissions has to be set in the Application in Microsoft Entra ID
1. Register your application
To call Microsoft Graph, your app must acquire an access token from the Microsoft identity platform. Learn more about this -
- Authentication and authorization basics for Microsoft Graph
- Register your app with the Microsoft identity platform
Usage
Authentication
The default implementation of this module uses app-only access via the OAuth 2.0 client credentials flow and therefore requires Microsoft Graph application permissions. By default, the MicrosoftGraph authentication alias is used together with the .default scope. The alias is provided by this module and must be created and configured in the system.
You can also pass a custom Authentication config to the GraphClient constructor.
The passed Authentication Config has to be provided by the system.auth JDito Module.
Check the offical (Help Platform) for further informations
//with special Auth
const tokenAuth = auth.createConfigForOAuth2().token(mySecretToken);
let clientWithCustomAuth = new GraphClient(null, tokenAuth);
//with custom scope
let aliasAuth = auth.createConfigForOAuth2WithAlias()
.aliasName("MicrosoftGraph")
.scope("https://graph.microsoft.com/.default");
let client = new GraphClient(null, aliasAuth);
The authentication config can also be with the setAuthByAlias function of the GraphClient instance
let client = new GraphClient().setAuthByAlias("MyCustomGraphAlias", "https://graph.microsoft.com/.default");
Instance Configuration
In order to work out of the box, some default instance preferences are required.
Ensure that the following are set within your project:
| Key | Description | Example |
|---|---|---|
microsoftGraphApi.BaseURL | The Base URL of the Microsoft Graph API. | https://graph.microsoft.com |
microsoftGraphApi.version | The default API version used by Microsoft Graph. | v1.0 |
microsoftGraphApi.defaultAuthAlias | The name of the default authentication alias. | MicrosoftGraph |
microsoftGraphApi.defaultScope | The default scope used for authentication. | https://graph.microsoft.com/.default |
You can override these defaults per instance if necessary, but keeping them consistent across environments is recommended.
Graph Client
A new GraphClient instance has to be created. An existing instance can be used for multiple requests.
When no Authconfig is passed the default Alias Auth is used.
The constructor accepts 2 parameter:
pConfigConfiguration objectpAuthConfigauth object -> check Authentication for more information
pConfig
In the config object you can currently set 2 properties
debug{boolean} controlls if debug messages are loggedapi{string} overwrite the default graph api versions possible values arev1.0andbeta
let graphClient = new GraphClient({debug : true}, customAuthObject);
let myData = graphClient.api("/me").get();
Calling
The outgoing REST Request is chained together baseUrl + path + QueryParameter
You can log the outgoing REST Request by setting the debug property in the GraphClient instance
let options = { debug: true };
let graphClient = new GraphClient(options);
Supported Paths
.api() is flexible in it's path parameter the following versions are supported
me/mehttps://graph.microsoft.com/v1.0/mehttps://graph.microsoft.com/beta/mehttps://graph.microsoft.com/v1.0/me?$select=displayName
const graphClient = new GraphClient();
graphClient.api("me").get();
graphClient.api("/me").get();
graphCient.api("https://graph.microsoft.com/v1.0/me?$select=displayName").get();
ContentTypes
The default content types for requests are
application/jsonfor dataType Accept and dataTypeSendutil.DATA_TEXTfor dataTypeJDitoAccept and dataTypeJDitoSend
The content type can be set with .contentType({dataTypeSend: MimeTypes.JSON()})
let myContentType = {
dataTypeSend: MimeTypes.JSON(),
dataTypeAccept: MimeTypes.JSON() };
new GraphClient()
.api("/me")
.contentType(myContentType)
.get();
Header
Custom headers can be set by the header(pKey, pValue) function
get
Makes a HTTP GET Request. Additonal QueryParameter or Header set by the GraphRequest class are passed to the Request.
let contactFolder = `users/${UserPrincipal}/contactFolders/${folderID}/contacts`;
let options = { debug: true};
let graphClient = new GraphClient(options);
let contactData = graphClient
.api(contactFolder)
.select("emailAddresses")
.filter("startswith(displayName,'Peter Shaw')")
.get();
post
Makes a HTTP POST Request. Additonal QueryParameter or Header set by the GraphRequest class are passed to the Request.
The post(pContent) Method requires a parameter which contains the content for the POST request.
const contactFolder = `users/${UserPrincipal}/contactFolders/${folderID}/contacts`;
let contact = {
"givenName": "Robert",
"surname": "Andrews",
"nickName": "Bob",
"companyName": "Aquire GmbH",
"emailAddresses": [
{
"address": "bob@fragezeichen.de",
"name": "Bob Andrews"
}
],
"businessPhones": [
"+49 1575 1234 22"
]
};
let graphClient = new GraphClient()
.api(contactFolder)
.post(JSON.stringify(contact));
patch
Makes a HTTP PATCH Request. Additonal QueryParameter or Header set by the GraphRequest class are passed to the Request.
The .patch(pContent) Method requires a parameter which contains the content for the POST request.
let patchData = {
"companyName": "T. Jonas GmbH"
}
let patchResponse = graphClient
.api(contactIdPath)
.patch(patchData);
put
Makes a HTTP PUT Request. Additonal QueryParameter or Header set by the GraphRequest class are passed to the Request.
The .patch(pContent) Method requires a parameter which contains the content for the POST request.
delete
Makes a HTTP DELETE Request. Additonal QueryParameter or Header set by the GraphRequest class are passed to the Request.
Query parameter
An overview of all possible Query Parameter can be found Customize Microsoft Graph responses with query parameters
The default supported oData Queryparameter are
selectexpandorderByfiltercounttop
.select(pProperty)
Adds the select oData QueryParameter to the Request. Use the $select query parameter to return a subset of properties for a resource.
Possible Usage:
.select("displayName,birthday")
.select(["displayName", "birthday"])
.select("displayName", "birthday")
.expand(pProperty)
Adds the expand oData QueryParameter to the Request.
Example
.expand("contacts")
.orderBy(pProperties)
Add properties for orderBy OData Query param
Specify the sort order of the items returned from Microsoft Graph. The default order is ascending.
Example:
.orderBy("displayName asc")
.orderBy("createdDateTime,displayName")
.orderBy(["displayName desc", "createdDateTcime asc"])
.filter(pProperty)
Adds a query string for OData Query param - Graph only accepts one $filter Odata Query option it's value is set to the most recent passed filter
.filter("companyName eq 'ADITO'")
.count(pCount:boolean)
Sets the count OData Query param - Graph only accepts one $count Odata Query option it's value is set to the most recent passed number Returns the total count of matching resources.
.count(true)
.top(pNumber)
Adds a number for top OData Query param - Graph only accepts one $top Odata Queryoption it's value is set to the most recent passed number.
Sets the page size of the result
.top(10)
Besides the provided oData Query parameter you can also pass other Query Parameter supported by the API
.query
With the .quey(pQuery) you can pass aditional query parameter to the request
The pQuery parameter supports a string as well as a key value pair object
const ressource = "/me/contacts";
let contactData = graphClient
.api(ressource)
.select("displayName")
.query("$filter=startswith(displayName,'Peter Shaw')")
.get();
let contactData2 = graphClient
.api(ressource)
.select("displayName")
.query({"$filter": "startswith(displayName,'Peter Shaw')"})
.get();
Batching
The Microsoft Graph API provides a way to batch multiple requests (up to 20 per batch) into a single web service call.
This helps reduce network traffic and improves performance when multiple requests need to be executed.
This module provides the helper function processBatch() to simplify sending batch requests to the Microsoft Graph API.
processBatch() sends the provided request objects to the Graph $batch endpoint.
Important
The Microsoft Graph batch endpoint supports a maximum of 20 requests per batch.
If more requests need to be processed, they must be split into chunks of up to 20 requests before calling this function.
let batchData = [{
id: 1, url: "/me/contacts", method: "GET", "headers": {
"Content-Type": "application/json"
}
},
{
id: 2, url: "users/${pMailBox}/contactFolders/", method: "GET", "headers": {
"Content-Type": "application/json"
}
}];
let graphBatch = new GraphClient({ debug: true }, pGraphAuthConfig)
.processBatch(batchData);
If no id is provided in the request object, the function automatically assigns one. If more than 20 requests must be processed, the calling module should split the requests into multiple batches.
Check the official documentation for detail information about Batching
Throttling
Throttling must be explicitly considered and implemented within the respective modules. The reason for this is that, depending on the situation, an appropriate and dynamic reaction is required.
Throttling occurs when a high number of requests are sent to a single Graph resource within a short period of time. In such cases, the API responds with HTTP status code 429 (Too Many Requests) and includes a Retry-After header indicating when it is allowed to send the next request.
A good practice is to stop further requests to the API when throttling is detected.
More Information about (Throttling)[https://learn.microsoft.com/en-us/graph/throttling#throttling-and-batching]
How to use this Module
In your desired Module add the dependency @aditosoftware/microsoft-graph-api
Now you can use the constructor new GraphClient() in your libaries.
Check the microsoft-graph-contactsync module or other modules within the microsoft-graph subgroup in gitlab for a possible implementation