r/GraphAPI • • Dec 12 '24

Graph API for mailboxsettings

1 Upvotes

I am trying to enable Autoreply on a user's mailbox using the Graph API for an automation, but I am encountering an "access denied" error. I am a global admin and have already granted the appropriate permissions. I was wondering if anyone here has experience automating this specific
setting.

Example https://graph.microsoft.com/v1.0/users/[email protected]/mailboxSettings

{
    "error": {
        "code": "ErrorAccessDenied",
        "message": "Access is denied. Check credentials and try again."
    }
}

r/GraphAPI • • Dec 04 '24

Filter / Sort OneDrive/SharePoint Files

1 Upvotes

Hi everyone,

I’m integrating my app with SharePoint and need to retrieve all files visible to a user, including those in nested directories. For this, I’ve been using the next API with empty search params

/me/drive/root/search

Now, we want to support filtering and sorting with more complex conditions. For example, I need to retrieve a list of files that:

  • Were created by the current user,

  • Were modified within the last week,

  • Contain a specific text in the file name,

  • Have a specific file format (or one of several formats),

  • And return the results sorted in a particular order.

I think I need to use a different API for this functionality. Does anyone have experience with such use cases? Which API would be the most appropriate for filtering and sorting files in this way, and how would you structure the request?

Thanks in advance!

Maybe this API will cover my case?

v1.0/search/query

{
    "requests": [
        {
            "entityTypes": [
                "driveItem"
            ],
            "query": {
                "queryString": "(filetype:docx OR filetype:doc) AND ..."
            }
        }
    ]
}

r/GraphAPI • • Nov 06 '24

Question regarding what '-DeviceID' New-MgDeviceRegisteredOwnerByRef is requesting

1 Upvotes

Hey all, trying to figure out what Device ID that New-MgDeviceRegisteredOwnerByRef is needing.

I tried entering all versions of the ID I could see when running

GET https://graph.microsoft.com/v1.0/deviceManagement/managedDevices

but none of the IDs seem to work, I just get the error

Get-MgDeviceRegisteredOwner : Resource '{UID}' does not exist or one of its queried reference-property objects are not present.

Status: 404 (NotFound)

Any help would be greatly appreciated!


r/GraphAPI • • Oct 29 '24

Can I use either Microsoft Graph API or REST/PNP in SPFx to update a metadata column in a list item?

1 Upvotes

I've been trying to update a managed metadata (taxonomy) column in a SharePoint list item through SPFx, using both the Microsoft Graph API and REST/PNP approaches. I’ve tested various payload formats and methods that were suggested in forums and documentation, but nothing has worked so far. Has anyone managed to get either method working for this purpose, or is there another workaround that I’m missing? Examples or insights would be hugely appreciated! Thanks in advance.


r/GraphAPI • • Oct 24 '24

Cannot add users to mail-enabled groups using Zapier

1 Upvotes

Hello everyone, I've been trying to automate the onboarding process for my company but GraphAPI doesn't seem to be supporting user addition to mail-enabled groups.... Do you guys know any workaround for this?


r/GraphAPI • • Oct 24 '24

Discrepancy between Get-AuditLogSignin Vs Get-MgUser with regard to Interactive Sign-ins

1 Upvotes

I'm working on a script that has produced a discrepancy between data found in Entra. This has been consistent with users.

Here's the script:

# Get user details with SignInActivity
$user = Get-MgUser -UserId $userId -Property SignInActivity,DisplayName,UserPrincipalName

# Display the sign-in activity
$user | Select-Object DisplayName, UserPrincipalName,
    @{Name='LastSignInDateTime';Expression={$_.SignInActivity.LastSignInDateTime.ToLocalTime()}},
    @{Name='LastNonInteractiveSignInDateTime';Expression={$_.SignInActivity.LastNonInteractiveSignInDateTime.ToLocalTime()}} |
    Format-Table -AutoSize

Entra shows the last interactive sign in as 10/22/24 at 2:51 pm but the results of the Get-Mguser script above are as follows:

Has anyone run into this and have an explanation of why a discrepancy exists?


r/GraphAPI • • Oct 24 '24

Where to find Profiles created under "Endpoint Security" (Intune) in Graph?

1 Upvotes

Hi There :-)

I was recently asked by a colleague for a way to find out which devices do not have a certain Defender Firewall Policy assigned which was created in Intune under “Endpoint Security” --> “Firewall”

I was thinking of Graph. However, when I tried to find out the corresponding ID of the profile, i realized that these profiles are not listed under: “https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations”.

ChatGPT couldn't really help me here either, or rather it suggested “https://graph.microsoft.com/v1.0/deviceManagement/endpointSecurity/firewallPolicies”, which was acknowledged in graph with “Resource not found for the segment ‘endpointSecurity’.”.

Can anyone tell me where I can find those kind of profiles in Graph?


r/GraphAPI • • Oct 16 '24

Trying to copy Teams Channel POST to another Channel and cannot copy hostedContent

1 Upvotes

I have a Teams Channel where I need to copy the POSTS to another Channel. I am using MS Graph API. Trying to copy the HostedContent (3 embedded img tags) throws an error. Combined, they exceed the 4194304 stream size limit.

Creating the POST without the hosted content, then going back and Updating that POST 3 times with each content doesn't work.

How do I get the HostedContents copied over? (would be nice if I could also make the new post as the original user)

    $url = "https://graph.microsoft.com/v1.0"
    $val = '$value'
    $quot = '"'

    $msgbody = $msg.body.content

    $uri = "$url/teams/$srcteamid/channels/$srcchannelid/messages/$($msg.id)/hostedContents"
    $hostedContents = (Invoke-MgGraphRequest -Uri $uri -Method GET).value
    if ($hostedContents -ne $null) {
        ForEach ($hc in $hostedContents) {
            $uri = "$url/teams/$srcteamid/channels/$srcchannelid/messages/$($msg.id)/hostedContents/$($hc.id)/$val"
            Invoke-MgGraphRequest -Uri $uri -Method GET -OutputFilePath "$($hc.id).png"
        }

        $HostedContentArray = @()
        $img = 0
        $totsize = 0
        $idx = 1
        While ($idx -lt $hostedContents.Length) {
            $hc = $hostedContents[$idx]
            $contentid = $hc.id
            $imgsize = (Get-Item "$contentid.png").Length
            if ($totsize + $imgsize -le 4194304) {
                $totsize += $imgsize
                $img++
                $txt = "$url/teams/$srcteamid/channels/$srcchannelid/messages/$($msg.id)/hostedContents/$contentid/$val"
                $txt = $txt.replace(".", "\.").replace("/", "\/").replace("$", "\$")
                $patt = "src=$quot$txt$quot"
                $msgbody = $msgbody -replace $patt, "src=$quot../hostedContents/$img/$val$quot"

                $obj = @{
                    "@microsoft.graph.temporaryId" = "$img"
                    contentBytes = [System.Convert]::ToBase64String([IO.File]::ReadAllBytes("$contentid.png"))
                    contentType = "image/png"
                }
                $HostedContentArray += $obj
            }
            $idx++
        }
    }

    $msg_datetime = [TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($msg.createdDateTime, 'Eastern Standard Time')
    $msg_subject = "ON $msg_datetime, $($msg.from.user.displayName) posted: $($msg.subject)"
    $uri = "$url/teams/$destteamid/channels/$destchannelid/messages"
    $params = @{
        subject = $msg_subject
        body = @{
            contentType = $msg.body.contentType
            content = $msgbody
        }
        importance = $msg.importance
        mentions = $msg.mentions
        from = $msg.from
    }
    if ($HostedContentArray.length -gt 0) {
        $params.hostedContents = $HostedContentArray
    }

    $dest_msg = Invoke-MgGraphRequest -Uri $uri -Method POST -Body $params

            $msgbody = $dest_msg.body.content
            $img = 0
            $idx = 0
            $HostedContentArray = @()
            $hc = $hostedContents[$idx]
            $contentid = $hc.id
                $img++
                $txt = "$url/teams/$srcteamid/channels/$srcchannelid/messages/$($msg.id)/hostedContents/$contentid/$val"
                $txt = $txt.replace(".", "\.").replace("/", "\/").replace("$", "\$")
                $patt = "src=$quot$txt$quot"
                $msgbody = $msgbody -replace $patt, "src=$quot../hostedContents/$img/$val$quot"

                $obj = @{
                    "@microsoft.graph.temporaryId" = "$img"
                    contentBytes = [System.Convert]::ToBase64String([IO.File]::ReadAllBytes("$contentid.png"))
                    contentType = "image/png"
                }
                $HostedContentArray += $obj

            $params = @{
                subject = $msg_subject
                body = @{
                    contentType = $msg.body.contentType
                    content = $msgbody
                }
                hostedContents = $HostedContentArray
            }
            $uri = "$url/teams/$destteamid/channels/$destchannelid/messages/$($dest_msg.id)"
            Invoke-MgGraphRequest -Uri $uri -Method PATCH -Body $params

r/GraphAPI • • Oct 08 '24

Empty response to Graph query on mails in a folder which actually has mail items visible in mailbox!!

1 Upvotes

r/GraphAPI • • Oct 04 '24

Get free/busy of external shared calendar

1 Upvotes

Hi, An external user, either a different workplace or private, i.e. outlook.com etc) shared their calendar free/busy with me. I'm currently struggling with 2 things:

  1. Is there a way to accept the invite using the graph API?

  2. Once accepted, how can I see their free/busy status?

For point 1, I think I can look at my messages in the API, but how can I get alerted that I got an invite message?

For number 2, I used the getSchedule endpoint but I get error messages 5009 that the user couldn't be found in active directory, which is correct because they're external to my org.

I'm new to using graph API so any help would be really appreciated 😊


r/GraphAPI • • Oct 03 '24

Exchange 365 users with additional access/permission

1 Upvotes

Hi,
is there a way to get the users with access permissions on other mailboxes other than their own using REST API?

Some IT members gave access to users to other users' mailboxes. Since I have thousands of mailboxes to check, I would prefer an audit via API REST.

Thank you.


r/GraphAPI • • Oct 03 '24

Revoke user tokens and delegated access scopes

1 Upvotes

Heya there,

So, i'm developing a web application that calls some ms graph endpoints, and uses delegated auth. I store the access + refresh tokens and use those in the background.

At some point in the future, the user may want to revoke the access he gave to my application. The problem here is that i cannot seem find an endpoint to call for me to do this programatically - i could redirect the user to the Microsoft privacy/app-access page , and he revokes it there manually, however this is bad for me as my web app cannot know that the access has been removed.

I can't find a straightforward explanation on the API docs, is there any way to actually do this? I do not want to use the /revokeSignInSessions nuclear approach.


r/GraphAPI • • Oct 01 '24

Moving mail from shared mailbox to another shared mailbox

1 Upvotes

At the moment i use a pywin script to move al completere from all our 10+ mailboxen top one General subfolder of a shared mailbox. This saves us lots of time searching for mails. The same we do for sent items.

Since that i have full admin access to our graph api, I would rather to this process with the GraphAPI of course.

But as far as my research goes this is simply not possible. Do you guys know a way to achieve this with the API, or a way around? Or should we stick with the pywin script. Or a better way of work?


r/GraphAPI • • Sep 27 '24

AutopilotDeviceIdentity Search by Serial

1 Upvotes

I am trying to search the list of devices in the windowsAutopilotDeviceIdentities list by serial. In the docs it just shows you can search by the ID, is there a way to search by a devices serial? Thanks for your help!


r/GraphAPI • • Sep 25 '24

Graph Batch Request & Azure App Service Failing

1 Upvotes

I have a batch request that works flawlessly when I'm debugging on IIS Express, but as soon as I publish to an Azure App Service the batch returns error 400 for every request in the batch.

The max number of user calendars I'm requesting is around 10, but it fails even if I just add 1 to the batch. I can pull individual calendars using CalendarView.GetAsync locally or on the app service so it's definitely something with the batch request.

List<string> eventRequests = [];

foreach (var user in users)

{

var eventRequest = graphClient.Users[user.UserPrincipalName].CalendarView

.ToGetRequestInformation(requestConfiguration =>

{

requestConfiguration.QueryParameters.StartDateTime = startTime.ToString();

requestConfiguration.QueryParameters.EndDateTime = endTime.Value.ToString();

});

eventRequests.Add(await batchRequestContent.AddBatchRequestStepAsync(eventRequest, user.UserPrincipalName));

}

var returnedResponse = await graphClient.Batch.PostAsync(batchRequestContent);


r/GraphAPI • • Sep 10 '24

Trying to use Graph to pull user/device ownership for BI report

1 Upvotes

HR requested a report showing all users whom have registered devices under their account. Trying to leverage PowerBI/Fabric to tap into graph and pull tables that have enough data to associate a device (or multiple devices) with a user for compensation purposes. Anyone here have any ideas on the matter? I can pull devices and I can pull users, but I do not have any clue as to a way to associate them without running graph calls against specific device IDs or user principal names.


r/GraphAPI • • Sep 02 '24

[ Help Needed ] Need a Graph API to update device ownership of a device using .NET

1 Upvotes

Hi everyone,

I am looking to update device ownership of a device in AAD using Microsoft Graph API

This closest I have come to is https://learn.microsoft.com/en-us/graph/api/device-post-registeredowners?view=graph-rest-1.0&tabs=csharp but this needs delegated permission.

I would like to do it directly using Application permission type because I have to do the ownership change using a background process without any user involvement.

Note: My devices are not managed by Intune


r/GraphAPI • • Aug 19 '24

PowerBi Odata from Graph, for Sites

1 Upvotes

Following numerous tutorials online, I have successfully configured a query in PowerBi to connect to Microsoft Graph and pull down a list of SharePoint Online Sites (and subsites). It uses a Azure app to provide the relevant permissions to get the data, with a shared seceret for authentication.

Here's the advanced query:

let 
    resource="https://graph.microsoft.com",
    tokenResponse = Json.Document(Web.Contents("https://login.windows.net/",
    [
        RelativePath = #"Tenant ID" & "/oauth2/token",
        Content = Text.ToBinary(Uri.BuildQueryString(
            [
                client_id = #"Azure Application ID",
                resource = resource,
                grant_type = "client_credentials",
                client_secret = #"Azure Application Client Secret"
            ]
        )),
        Headers = [Accept = "application/json"], ManualStatusHandling = {400}
    ])),
    access_token = tokenResponse[access_token],
    Source = OData.Feed("https://graph.microsoft.com/beta/sites", [ Authorization = "Bearer " & access_token ], [ ExcludedFromCacheKey = {"Authorization"}, ODataVersion = 4, Implementation = "2.0" ]),
    #"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1, Int64.Type)
in
    #"Added Index"

Next I want to reduce the amount of data being imported, to speed things up. No point importing all of it and then filtering it, its going to be slow.

The most obvious filter to start with is ignoring OneDrive sites by checking 'isPersonalSite' = FALSE. No matter syntax I try, it does not work.

Alternatively, looking in the 'id' for only <domainname>.sharepoint.com. ignoring all those that are <domainname>-my.sharepoint.com.

Any suggestions on how to get one of these working with Sites? (Ideally the 'isPersonalSite' one)

Thanks in advanced for ideas and suggestions :)


r/GraphAPI • • Aug 14 '24

Graph API upload files with column (meta)data via JAVA

1 Upvotes

Hello everyone,

I have been trying to find a programmatic way of uploading a file or multiple files to a SharePoint Site, which contains also some column data. The core goal that I have is to iterate through local files, which are mapped in a way to a CSV and then import them with the respective metadata into SP.

Power Automate takes 30+ seconds to map the CSV data, so this is not really an option.

I have been looking around the MS documentation and tutorials and the closest thing I found is this - https://learn.microsoft.com/en-us/graph/api/listitem-create?view=graph-rest-1.0&tabs=java 

Unfortunately this one is not exactly what I need, as this is a List and not a Site.

Further I am able to upload a file to OneDrive, but there seems to be no documented way for a file in SharePoint. I would guess it should look like this somehow:
graphClient.sites().bySiteId(ApplicationProperties.siteId) then add or put.

Please, if somebody could give me a direction, this will be greatly appreciated.

Thank you!


r/GraphAPI • • Aug 05 '24

Filters in Microsoft GraphAPI not wroking as expected and giving strange results

1 Upvotes

The Query below applies filter that timeOff entries'
sharedTimeOff/startDateTime >= formattedTodayDateTime and
sharedTimeOff/endDateTime <= formattedRequiredEndDateTime

which translates to formattedTodayDateTime <= timeOff's start_date and end_date <= formattedRequiredEndDateTime.

This query gives number of entries in response (non empty) .

// headers and accessTokens approprately formed
params = Map();
params.put("$filter","sharedTimeOff/startDateTime ge " + formattedTodayDateTime + " and sharedTimeOff/endDateTime le " + formattedRequiredEndDateTime + "");
response = invokeurl
[
    url :graphUrl
    type :GET
    parameters:params
    headers:headers
];

In below query, I am filtering for timeoff entries such that,

formattedTodayDateTime <= timeOff's end_date <= formattedRequiredEndDateTime.

params = Map();
params.put("$filter","sharedTimeOff/endDateTime ge " + formattedTodayDateTime + " and sharedTimeOff/endDateTime le " + formattedRequiredEndDateTime + "");
response = invokeurl
[
    url :graphUrl
    type :GET
    parameters:params
    headers:headers
];

Issue: Second query should give me more number of responses, but it gives me absolutely empty response.

I am expecting more entries in my response. But keep getting empty response.
I have tried changing query to formattedTodayDateTime <= timeOff's end_date <= formattedRequiredEndDateTime, this also gives me empty response.


r/GraphAPI • • Jul 26 '24

Delete emails tenant wide based on Subject/Sender

1 Upvotes

We are exploring Graph API capabilities where we can delete emails tenant-wide based on the subject/sender email address. We have tried PowerShell content search/purge and it works as expected but we need Graph API for automation.

Any insights?


r/GraphAPI • • Jul 25 '24

Change Notifications API - What constitutes a notification?

1 Upvotes

I'm working with the Change Notifications API and it's not clear to me what changes will trigger a notification.

Specifically, for the User resource, I assume it notifies when the default User Properties change, but does it also include:

In my use case, for each user I have to fetch a bunch of relationships, it'd be great if I could rely on the notifications API to trigger a fetch of these, as needed, rather than polling 24/7.

I know I'm being optimistic here, just wondering if anyone has tested this.


r/GraphAPI • • Jul 24 '24

Getting Disposition stages for labels not working

1 Upvotes

I am beating my head against a wall. Does anyone have an explanation for the following:

Using https://graph.microsoft.com/v1.0/security/labels/retentionLabels/ I get a proper list of retention labels

Using https://graph.microsoft.com/v1.0/security/labels/retentionLabels/{retentionLabel-id} I get

"Internal error occured while calling AdminApi"

Using https://graph.microsoft.com/v1.0/security/labels/retentionLabels/{retentionLabel-id}/dispositionReviewStages I get

"{"Message":"No HTTP resource was found that matches the request URI 'https://substrate.office.com:444/complianceWorkbench/security/labels/retentionLabels('XXXXXXXXXXXXXXXX')/dispositionReviewStages'.","MessageDetail":"No type was found that matches the controller named 'retentionLabels'."}",

Using Powershell using Get-MgSecurityLabelRetentionLabel works to list the labels. Trying to access a specific label with Get-MgSecurityLabelRetentionLabel -RetentionLabelId "xxxxx" gets the same adminapi error as above.

The only result online I can find is this: https://learn.microsoft.com/en-us/answers/questions/1381375/unable-to-get-retention-label-by-id

It seems maybe the Graph API is just being left broken?


r/GraphAPI • • Jul 24 '24

Generate Script in mggraph with Ad account authentication

1 Upvotes

Hello,

I am little bit new on developing in MGGRAPH. I have to develop a script for key management of app registration and keeping the same Key Id, this feature is only possible with MgGraph.

I tried with Az library and was not able to keep the same Key ID.

In MgGraph i was able to delete the old Secret and generate a new one and specify the Key ID.

The problem i am facing i want to automatise this process with CyberArk CPM platform and use connect-mggraph with an active Directory service account but i dont find user authentication for mggraph.

I am already aware of the existence of a CyberArk platform is for Key management but the key management require global admin or application admin right and in a security point of view is not a good practice. If an user rename the app id with another app id they can be able to reset the secret of other assets.

If we segregate with specific service account we can put as owner of the app registration the service account and manage only the Secret of the app registration were this service account is owner. Without exposing all our app registration secret.