6

I'm trying to get access to SharePoint team sites of an organization. I'm using Microsoft Graph API as it's the most complete API for Office 365. I understand how to get an access token and how to use it to make requests. I know it works because I can get a list of groups but when it comes to get all team sites I get an error message:

Code : invalidRequest    
Message : Cannot enumerate sites

Here is my code. I'm testing it out in a console application.

class Program {
    static void Main(string[] args) {
        Program p = new Program();
        var items = p.GetItems();
        items.Wait();
        foreach (var item in items.Result) {
            Console.WriteLine(item.DisplayName);
        }

        Console.ReadLine();
    }

    public async Task<IGraphServiceSitesCollectionPage> GetItems() {
        PublicClientApplication myApp =
            new PublicClientApplication("CLIENT-ID-FROM-DEVELOPPER-CONSOLE");

        //Gets an access token
        AuthenticationResult authenticationResult =
            await myApp.AcquireTokenAsync(
                new string[] {
                    "user.read.all",
                    "sites.read.all",
                    "files.read.all",
                    "group.read.all",
                    "Directory.Read.All"
                }).ConfigureAwait(false);

        //Creates the client with the access token
        GraphServiceClient graphClient = new GraphServiceClient(
            new DelegateAuthenticationProvider(
                async(requestMessage) => {
                    // Append the access token to the request.
                    requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("bearer",
                            authenticationResult.AccessToken);
                }));

        //Requests the site objects
        var sites = await graphClient.Sites.Request().GetAsync();

        return sites;
    }
}

I Googled a lot and only found solutions that didn't work for me.

Marc LaFleur
  • 31,987
  • 4
  • 37
  • 63
Yan Lamothe
  • 65
  • 1
  • 5

1 Answers1

12

The error message is giving you an accurate description of why this isn't working.

The call to graphClient.Sites.Request().GetAsync() is translated into the HTTP call https://graph.microsoft.com/sites which isn't a valid API endpoint.

You need to provide some additional context such as which site you're looking for. For example, to get the Root Site you would call:

graphClient.Sites["root"].Request().GetAsync();

If you're looking for a Team Site you could use the site's path:

await graphClient.Sites["root"].SiteWithPath("/teams/myawesometeam").Request().GetAsync();

For additional SharePoint Endpoints, see the Graph SharePoint documentation.

Marc LaFleur
  • 31,987
  • 4
  • 37
  • 63