Adrian Ganea
Adrian Ganea

Reputation: 33

Create a folder inside a SharePoint Online list using graph api

I have a requirement of creating list items inside folders(folders will have unique permissions and hence the requirement). The second requirement is to be able to share the parent folders with external users.

Is it possible to create folders(and share them externally) in the root of a SharePoint Online list via the graph API? I can't seem to find a suitable method to achieve it.

I know this should be doable using the SharePoint REST API but I couldn't find a way to use the API from a client application (e.g. I tried using PowerShell with appregistration/Oauth to get access tokens but it didn't work with SPO, however it worked with graph)

Later edit:

Based on @Sridevi's feedback, I ended up using a combination of PnP and graph commands:

  1. add external user to my tenant using graph api
cls
$SiteURL="https://your_domain.sharepoint.com/sites/your_site/"
$ClientID = "00000000-0000-0000-0000-000000000000"

$tenantdomain="your_domain.onmicrosoft.com"
$ClientSecret = "base64 string"
$tenantid="12345678-1234-1234-1234-123456789999"
$thumbprint="06D3488F67CC8F90B2CA2C0DE48AB354E0E4259A"

#API info
$loginURL = "https://login.microsoftonline.com/"
$resource = "https://graph.microsoft.com"

# Get an Oauth 2 access token based on client id, secret and tenant domain
$body = @{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret}
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token?api-version=1.0 -Body $body

#Let's put the oauth token in the header, where it belongs
$headerParams  = @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"}

#GET 
$uri ="https://graph.microsoft.com/v1.0/invitations"


$body = @{
    invitedUserDisplayName="test";invitedUserEmailAddress="[email protected]";sendInvitationMessage=$false;inviteRedirectUrls="https://myapp.com"
}
$jsonBody = $body | ConvertTo-Json

$tenantInfo = (Invoke-RestMethod -Uri $uri –Headers $headerParams –Method Post –Verbose -Body $jsonBody)
  1. grant newly added external user permissions to list folder
cls
$SiteURL="https://your_domain.sharepoint.com/sites/your_site/"
$ClientID = "00000000-0000-0000-0000-000000000000"

$tenant="your_domain.onmicrosoft.com"
$ClientSecret = "base_64 string here"

#Connect-PnPOnline -Url $SiteURL -ClientId $ClientID -ClientSecret $ClientSecret

$conn=Connect-PnPOnline -Url $SiteURL -ClientId $ClientID  -Thumbprint $thumbprint -Tenant $tenant -ReturnConnection
#-UseWebLogin  #



$folder="List folder name"
$externalUser="[email protected]"
#create HQ folder
#Add-PnPFolder -Name $folder -Folder "Lists/YourList"


#share a folder





#add external user --RENAMED in newer version of PnP to Add-PnPGroupMember
# this api is not working, failing with message "Entra db error: no inviteEmail for invitation"
#Add-PnPUserToGroup -EmailAddress $externalUser -Identity "Test" -Connection $conn -SendEmail


#grant spfolder permissions
$spFolder = Get-PnPFolder -URL ("/sites/extranet/Lists/YourList/"+$folder)
Set-PnPFolderPermission -List "Outprocessing" -Identity $spFolder -User $externalUser -AddRole "Contribute"

Upvotes: 0

Views: 357

Answers (1)

Sridevi
Sridevi

Reputation: 22432

Initially, register one Entra ID application and grant Sites.ReadWrite.All permission of Application type as below:

enter image description here

I have one document library with below files in SharePoint site named sridemosite :

enter image description here

To create new folder inside above SharePoint Online list using Graph API, you can make use of below PowerShell script:

$siteId = "your-site-id"
$listId = "your-list-id"
$folderName = "DemoFolder"

# Obtain an access token
$tenantId = "your-tenant-id"
$clientId = "your-client-id"
$clientSecret = "your-client-secret"
$authUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$authBody = @{
    client_id     = $clientId
    client_secret = $clientSecret
    scope         = "https://graph.microsoft.com/.default"
    grant_type    = "client_credentials"
}
$response = Invoke-RestMethod -Method Post -Uri $authUrl -ContentType "application/x-www-form-urlencoded" -Body $authBody
$token = $response.access_token

# Create the folder
$uri = "https://graph.microsoft.com/v1.0/sites/$siteId/lists/$listId/drive/root/children"
$body = @{
    name = $folderName
    folder = @{}
    '@microsoft.graph.conflictBehavior' = "rename"
}
$jsonBody = $body | ConvertTo-Json
$response = Invoke-RestMethod -Method Post -Uri $uri -Headers @{Authorization = "Bearer $token"} -Body $jsonBody -ContentType "application/json"
$response

Response:

enter image description here

To confirm that, I checked the same in SharePoint Online list where folder created successfully as below:

enter image description here

To share this folder to external user, make use of below script that runs this API:

$folderId = $response.id
$driveId = "driveId"
$externalUserEmail = "[email protected]"

# Share the folder
$shareUri = "https://graph.microsoft.com/v1.0/sites/$siteId/drives/$driveId/items/$folderId/invite"
$shareBody = @{
    recipients = @(
        @{
            email = $externalUserEmail
        }
    )
    message = "Here's the file you requested."
    requireSignIn = $true
    sendInvitation = $true
    roles = @("read")
    password = $password
    expirationDateTime = $expirationDateTime
}
$jsonShareBody = $shareBody | ConvertTo-Json
$result = Invoke-RestMethod -Method Post -Uri $shareUri -Headers @{Authorization = "Bearer $token"} -Body $jsonShareBody -ContentType "application/json"

$result

Response:

enter image description here

This will send mail to external user with folder access as below:

enter image description here

Upvotes: 2

Related Questions