Kevin YANG
Kevin YANG

Reputation: 441

Can not create a team from scratch via microsoft graph api

I follow this document and tried to create a team in the code https://learn.microsoft.com/en-us/graph/api/team-post?view=graph-rest-1.0&tabs=csharp%2Chttp. here is my code snippets:

var scopes = new string[] { "https://graph.microsoft.com/.default" };

            // Configure the MSAL client as a confidential client
            var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithTenantId(tenantId)
                .WithClientSecret(clientSecret)
                .Build();
 GraphServiceClient graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
                {

                    // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
                    var authResult = await confidentialClient
                        .AcquireTokenForClient(scopes)
                        .ExecuteAsync();

                    // Add the access token in the Authorization header of the API request.
                    requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                })
                );

            // Make a Microsoft Graph API call
            var team = new Team
            {
                DisplayName = "My Sample Team",
                Description = "My Sample Team’s Description",
                AdditionalData = new Dictionary<string, object>()
    {
        {"[email protected]", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"},
        {"[email protected]", "[{\"@odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[\"owner\"],\"userId\":\"57d4fc1c-f0a3-1111-b41e-22229f05911c\"}]"}
    }
            };
 GraphServiceClient graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
                {

                    // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
                    var authResult = await confidentialClient
                        .AcquireTokenForClient(scopes)
                        .ExecuteAsync();

                    // Add the access token in the Authorization header of the API request.
                    requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                })
                );

            // Make a Microsoft Graph API call
            var team = new Team
            {
                DisplayName = "My Sample Team",
                Description = "My Sample Team’s Description",
                AdditionalData = new Dictionary<string, object>()
    {
        {"[email protected]", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"},
        {"[email protected]", "[{\"@odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[\"owner\"],\"userId\":\"57d4fc1c-f0a3-4105-b41e-1ba89f05911c\"}]"}
    }
            };

but get this error:

 "message": "Bind requests not supported for containment navigation property.",\r\n   

I'm using the latest Microsoft.Graph library and version is V3.1.8

does anyone have some ideas on this issue or the odata format error?

Upvotes: 1

Views: 818

Answers (1)

Allen Wu
Allen Wu

Reputation: 16458

It seems that the [email protected] is still in change. It doesn't work currently.

You need to use members property.

POST https://graph.microsoft.com/v1.0/teams

{
  "[email protected]":"https://graph.microsoft.com/v1.0/teamsTemplates('standard')",
  "displayName":"My Sample Team555",
  "description":"My Sample Team’s Description555",
  "members":[
      {
         "@odata.type":"#microsoft.graph.aadUserConversationMember",
         "roles":[
            "owner"
         ],
         "userId":"9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
      }
   ]
}

The corresponding C# code should be:

var team = new Team
            {
                DisplayName = "My Sample Team557",
                Description = "My Sample Team’s Description557",
                Members = (ITeamMembersCollectionPage)new List<ConversationMember>()
                {
                    new AadUserConversationMember
                    {
                        Roles = new List<String>()
                        {
                            "owner"
                        },
                        UserId = "9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
                    }
                },
                AdditionalData = new Dictionary<string, object>()
                {
                    {"[email protected]", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
                }
            };

Unfortunately, when I run the code, it shows:

System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.List`1[Microsoft.Graph.ConversationMember]' to type 'Microsoft.Graph.ITeamMembersCollectionPage'.'

I cannot make it work. The workaround is to use httpClient to send the request in your code.

See a similar question here.

UPDATE:

I have figured it out.

You can try the following code:

        var team = new Team
        {
            DisplayName = "My Sample Team558",
            Description = "My Sample Team’s Description558",
            Members = new TeamMembersCollectionPage() {
                new AadUserConversationMember
                {
                    Roles = new List<String>()
                    {
                        "owner"
                    },
                    UserId = "9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
                }
            },
            AdditionalData = new Dictionary<string, object>()
            {
                {"[email protected]", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
            }
        };

If you prefer httpClient method, refer to this:

        string str = "{\"[email protected]\":\"https://graph.microsoft.com/v1.0/teamsTemplates('standard')\",\"displayName\":\"My Sample Team999\",\"description\":\"My Sample Team’s Description555\",\"members\":[{\"@odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[\"owner\"],\"userId\":\"9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce\"}]}";

        var content = new StringContent(str, Encoding.UTF8, "application/json");

        HttpClient client = new HttpClient();
        
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        var response = client.PostAsync("https://graph.microsoft.com/v1.0/teams", content).Result;

UPDATE 2:

If you need to call it in Postman, use this format:

{
  "[email protected]":"https://graph.microsoft.com/v1.0/teamsTemplates('standard')",
  "displayName":"My Sample Team555",
  "description":"My Sample Team’s Description555",
  "members":[
      {
         "@odata.type":"#microsoft.graph.aadUserConversationMember",
         "roles":[
            "owner"
         ],
         "userId":"9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
      }
   ]
}

Upvotes: 2

Related Questions