Giter Club home page Giter Club logo

msgraph-sdk-go's Introduction

Microsoft Graph SDK for Go

PkgGoDev

Get started with the Microsoft Graph SDK for Go by integrating the Microsoft Graph API into your Go application!

Note: this SDK allows you to build applications using the v1.0 of Microsoft Graph. If you want to try the latest Microsoft Graph APIs under beta, use our beta SDK instead.

Note: The Microsoft Graph Go SDK is currently in General Availability version starting from version 1.0.0. The SDK is considered stable, regular releases and updates to the SDK will however continue weekly..

1. Installation

go get github.com/microsoftgraph/msgraph-sdk-go
go get github.com/microsoft/kiota-authentication-azure-go

2. Getting started

2.1 Register your application

Register your application by following the steps at Register your app with the Microsoft Identity Platform.

2.2 Create an AuthenticationProvider object

An instance of the GraphRequestAdapter class handles building client. To create a new instance of this class, you need to provide an instance of AuthenticationProvider, which can authenticate requests to Microsoft Graph.

For an example of how to get an authentication provider, see choose a Microsoft Graph authentication provider.

Note: we are working to add the getting started information for Go to our public documentation, in the meantime the following sample should help you getting started.

This example uses the DeviceCodeCredential class, which uses the device code flow to authenticate the user and acquire an access token. This authentication method is not enabled on app registrations by default. In order to use this example, you must enable public client flows on the app registation in the Azure portal by selecting Authentication under Manage, and setting the Allow public client flows toggle to Yes.

import (
    azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "context"
)

cred, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
    TenantID: "<the tenant id from your app registration>",
    ClientID: "<the client id from your app registration>",
    UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error {
        fmt.Println(message.Message)
        return nil
    },
})

if err != nil {
    fmt.Printf("Error creating credentials: %v\n", err)
}

2.3 Get a Graph Service Client and Adapter object

You must get a GraphRequestAdapter object to make requests against the service.

import msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"

client , err  := msgraphsdk.NewGraphServiceClientWithCredentials(cred, []string{"Files.Read"})
if err != nil {
    fmt.Printf("Error creating client: %v\n", err)
    return
}

3. Make requests against the service

After you have a GraphServiceClient that is authenticated, you can begin making calls against the service. The requests against the service look like our REST API.

3.1 Get the user's drive

To retrieve the user's drive:

import (
    "github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors"
)

result, err := client.Me().Drive().Get(context.Background(), nil)
if err != nil {
    fmt.Printf("Error getting the drive: %v\n", err)
    printOdataError(err)
}
fmt.Printf("Found Drive : %v\n", *result.GetId())

// omitted for brevity

func printOdataError(err error) {
	switch err.(type) {
	case *odataerrors.ODataError:
		typed := err.(*odataerrors.ODataError)
		fmt.Printf("error:", typed.Error())
		if terr := typed.GetError(); terr != nil {
			fmt.Printf("code: %s", *terr.GetCode())
			fmt.Printf("msg: %s", *terr.GetMessage())
		}
	default:
		fmt.Printf("%T > error: %#v", err, err)
	}
}

4. Getting results that span across multiple pages

Items in a collection response can span across multiple pages. To get the complete set of items in the collection, your application must make additional calls to get the subsequent pages until no more next link is provided in the response.

4.1 Get all the users in an environment

To retrieve the users:

import (
    msgraphcore "github.com/microsoftgraph/msgraph-sdk-go-core"
    "github.com/microsoftgraph/msgraph-sdk-go/users"
    "github.com/microsoftgraph/msgraph-sdk-go/models"
    "github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors"
)

result, err := client.Users().Get(context.Background(), nil)
if err != nil {
    fmt.Printf("Error getting users: %v\n", err)
    printOdataError(err)
    return err
}

// Use PageIterator to iterate through all users
pageIterator, err := msgraphcore.NewPageIterator[models.Userable](result, client.GetAdapter(), models.CreateUserCollectionResponseFromDiscriminatorValue)

err = pageIterator.Iterate(context.Background(), func(user models.Userable) bool {
    fmt.Printf("%s\n", *user.GetDisplayName())
    // Return true to continue the iteration
    return true
})

// omitted for brevity

func printOdataError(err error) {
        switch err.(type) {
        case *odataerrors.ODataError:
                typed := err.(*odataerrors.ODataError)
                fmt.Printf("error: %s", typed.Error())
                if terr := typed.GetError(); terr != nil {
                        fmt.Printf("code: %s", *terr.GetCode())
                        fmt.Printf("msg: %s", *terr.GetMessage())
                }
        default:
                fmt.Printf("%T > error: %#v", err, err)
        }
}

5. Documentation

For more detailed documentation, see:

6. Issues

For known issues, see issues.

7. Contributions

The Microsoft Graph SDK is open for contribution. To contribute to this project, see Contributing.

8. License

Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT license.

9. Third-party notices

Third-party notices

msgraph-sdk-go's People

Contributors

1chrisaf avatar andrueastman avatar arunpassi avatar bakito avatar baywet avatar ddyett avatar dependabot[bot] avatar fey101 avatar github-actions[bot] avatar jasonjoh avatar jobala avatar ken5scal avatar michaelmainer avatar microsoft-github-policy-service[bot] avatar nicolas-cyfix avatar praetorian-thendrickson avatar release-please[bot] avatar rkodev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

msgraph-sdk-go's Issues

Issue with the size of the API surface of the models package

The way, this Go module and especially the models package are constructed, leads to severe issues with the go tooling (and linting).

We have a simple Go application where we added the functionality to send email notifications though the Microsoft Graph API using Mail.Send. So we added the necessary packages, namely:

import (
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	authentication "github.com/microsoft/kiota-authentication-azure-go"
	msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
	"github.com/microsoftgraph/msgraph-sdk-go/me/sendmail"
	"github.com/microsoftgraph/msgraph-sdk-go/models"
)

for this purpose.

The final code did what was expected (sending the mail), but it also made the duration for go test to jump from 7s to 8m 50s and the linting with golangci-lint to jump from 36s to 7m 13s in our Github Action pipeline.

We then changed the Graph API request to a "plain HTTP Post request" using the net/http package from the standard library (while still using github.com/Azure/azure-sdk-for-go/sdk/azidentity and github.com/microsoft/kiota-authentication-azure-go for the authentication) and we are back at the normal times for tests and linting.

Additional pointers for the excessive size of the github.com/microsoftgraph/msgraph-sdk-go/models package are the official documentation refuses to display the API because it is too large and also Github only shows the first 1000 files when listing the content of said package folder.

So in my opinion, the API surface of the package github.com/microsoftgraph/msgraph-sdk-go/models is way to broad and this should be refactored massively.

SearchWithQ(* string) returns err: 'uritemplate:55:invalid literals'

Calling the `SearchWithQ(* string) method so:

	searchString := "foo"
	drv, err := client.DrivesById(drvId).SearchWithQ(&searchString).Get(nil)

returns
'uritemplate:55:invalid literals'

It appears that the single quotes in

m.urlTemplate = "{+baseurl}/drive/microsoft.graph.search(q='{q}')";

are not recognized as valid characters by
https://github.com/yosida95/uritemplate/blob/3a84360807fa88737fe714e7ad55f7469ab8ecc9/parse.go#L45

Errors are not returned when application does not have the required scopes

I was trying this sdk to query groups. The Groups().Get() api fails and returns an empty set but err is not set.

       cred, err := azidentity.NewClientSecretCredential(
		<TenandID>,  // Removed for posting here
		<ClientID>,     // Removed for posting here
		<ClientSecret>, // Removed for posting here
		nil,
	)
	if err != nil {
		log.Printf("failed to get cred: %v\n", err)
		return err
	}

	auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(
		cred,
		[]string{"https://graph.microsoft.com/.default"},
	)
	if err != nil {
		log.Printf("failed to get identity: %v\n", err)
		return err
	}

	adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
	if err != nil {
		log.Printf("failed to get adapter: %v\n", err)
		return err
	}

	client := msgraphsdk.NewGraphServiceClient(adapter)
	result, err := client.Users().Get(nil)
	if err != nil {
		log.Printf("failed to get users: %v\n", err)
		return err
	}
        client := msgraphsdk.NewGraphServiceClient(adapter)

	resp, err := client.Groups().Get(nil)
	if err != nil {
		log.Printf("failed to get group: %v", err)
		return err
	}
       
       if (len(resp.GetValue()) == 0 {
                log.Printf("failed to get group")
       }

On debugging, I see http request failed with access denied as required scope for querying groups was not present. So error was returned in http request but was not propagated back to the caller.

On adding Directory.Read.All scope, it works fine and I get the groups. Problem is only not getting the error when it should be there.

build error

Hi, I tried the example in the doc,

package main

import (
	"fmt"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	a "github.com/microsoft/kiota/authentication/go/azure"
	msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
)

func main() {
	var err error

	cred, err := azidentity.NewClientSecretCredential(
		"",
		"",
		"",
		nil,
	)

	auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{"User.Read"})

	adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)  // an err happened here

	client := msgraphsdk.NewGraphServiceClient(adapter)
	result, err := client.Me().Get(nil)

	fmt.Println(err, "\n", auth)
}

go build failed with err shown bellow:

# github.com/microsoft/kiota/http/go/nethttp
C:\Users\a\go\pkg\mod\github.com\microsoft\kiota\http\go\[email protected]\nethttp_request_adapter.go:156:33: responseHandler.HandleResponse undefined (type abstractions.ResponseHandler has no field or method HandleResponse)
C:\Users\a\go\pkg\mod\github.com\microsoft\kiota\http\go\[email protected]\nethttp_request_adapter.go:182:33: responseHandler.HandleResponse undefined (type abstractions.ResponseHandler has no field or method HandleResponse)
C:\Users\a\go\pkg\mod\github.com\microsoft\kiota\http\go\[email protected]\nethttp_request_adapter.go:208:33: responseHandler.HandleResponse undefined (type abstractions.ResponseHandler has no field or method HandleResponse)
C:\Users\a\go\pkg\mod\github.com\microsoft\kiota\http\go\[email protected]\nethttp_request_adapter.go:252:33: responseHandler.HandleResponse undefined (type abstractions.ResponseHandler has no field or method HandleResponse)
C:\Users\a\go\pkg\mod\github.com\microsoft\kiota\http\go\[email protected]\nethttp_request_adapter.go:277:28: responseHandler.HandleResponse undefined (type abstractions.ResponseHandler has no field or method HandleResponse)

I don't know why it happened and how to fix it (i have search for this error but nothing useful found)

Error deserializing GET calendars response

Hi,
thanks for developing the Go SDK for Microsoft Graph. This is very helpful for me. Obtaining credentials via the device code login works fine, but once I request the list of calendars with client.Me().Calendars().Get(nil), the following error occurs:

panic: interface conversion: interface {} is graph.OnlineMeetingProviderType, not *graph.OnlineMeetingProviderType

goroutine 1 [running]:
github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph.(*Calendar).GetFieldDeserializers.func1({0x101352ea0, 0x140001c6100}, {0x10136d158, 0x14000013290})
	/Users/jfreymann/go/pkg/mod/github.com/microsoftgraph/[email protected]/models/microsoft/graph/calendar.go:209 +0x148
github.com/microsoft/kiota/serialization/go/json.(*JsonParseNode).GetObjectValue(0x140000134a0, 0x10135ae40)
	/Users/jfreymann/go/pkg/mod/github.com/microsoft/kiota/serialization/go/[email protected]/json_parse_node.go:171 +0x2a4
github.com/microsoft/kiota/serialization/go/json.(*JsonParseNode).GetCollectionOfObjectValues(0x14000013e80, 0x10135ae40)
	/Users/jfreymann/go/pkg/mod/github.com/microsoft/kiota/serialization/go/[email protected]/json_parse_node.go:196 +0x164
github.com/microsoftgraph/msgraph-sdk-go/me/calendars.(*CalendarsResponse).GetFieldDeserializers.func2({0x1013376c0, 0x1400018e600}, {0x10136d158, 0x14000013e80})
	/Users/jfreymann/go/pkg/mod/github.com/microsoftgraph/[email protected]/me/calendars/calendars_response.go:62 +0x44
github.com/microsoft/kiota/serialization/go/json.(*JsonParseNode).GetObjectValue(0x14000013e90, 0x10135ae38)
	/Users/jfreymann/go/pkg/mod/github.com/microsoft/kiota/serialization/go/[email protected]/json_parse_node.go:171 +0x2a4
github.com/microsoft/kiota/http/go/nethttp.(*NetHttpRequestAdapter).SendAsync(0x140000a81e0, {0x0, 0x0, 0x140000947b0, 0x140000947e0, {0x0, 0x0, 0x0}, 0x14000094720, {0x101263e73, ...}, ...}, ...)
	/Users/jfreymann/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/nethttp_request_adapter.go:158 +0x15c
github.com/microsoftgraph/msgraph-sdk-go/me/calendars.(*CalendarsRequestBuilder).Get(0x14000094780, 0x0)
	/Users/jfreymann/go/pkg/mod/github.com/microsoftgraph/[email protected]/me/calendars/calendars_request_builder.go:118 +0xac
main.main()

It seems like the deserializer for the response is not matching the actual JSON response. Could you please check if the generated code for the /calendars endpoint is correct?

Thanks and kind regards,

Jan Freymann

Page Iteration Example call for Graph Model Package

In the tutorial found at: https://docs.microsoft.com/en-gb/graph/sdks/paging?tabs=Go, the example gives instructions for printing out parts of a message.

When running the command: go get github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph, this is the result:

go: module github.com/microsoftgraph/msgraph-sdk-go@upgrade found (v0.19.1), but does not contain package github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph

The outcome is consistent with the current state of the repository. However, the current documentation does not provide insight on how to save a full struct effectively. (e.g. Mail: How to create a message object, Calendar: How to create a calendar appointment object)

unable to install msgraph-sdk-go

Hi

I am unable to install the sdk. The issue can easily be reproduced by using a docker container.

docker run --rm -it golang:1.17 bash
root@291304e6afd7:/go# go version
go version go1.17.8 linux/amd64
root@291304e6afd7:/go# go get -u github.com/microsoftgraph/msgraph-sdk-go
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/issues/item/incidentreport
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/issues/item/incidentreport/incident_report_request_builder.go:67:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/healthoverviews/item/issues/item/incidentreport
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/healthoverviews/item/issues/item/incidentreport/incident_report_request_builder.go:67:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/messages/archive
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/archive/archive_request_builder.go:70:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/messages/favorite
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/favorite/favorite_request_builder.go:70:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/messages/markunread
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/markunread/mark_unread_request_builder.go:70:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/messages/unfavorite
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/unfavorite/unfavorite_request_builder.go:70:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/messages/markread
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/markread/mark_read_request_builder.go:70:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/messages/item/attachments/item/content
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/item/attachments/item/content/content_request_builder.go:96:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/item/attachments/item/content/content_request_builder.go:108:47: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendNoContentAsync
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/messages/unarchive
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/unarchive/unarchive_request_builder.go:70:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
# github.com/microsoftgraph/msgraph-sdk-go/applications/delta
pkg/mod/github.com/microsoftgraph/[email protected]/applications/delta/delta_request_builder.go:68:54: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendCollectionAsync
pkg/mod/github.com/microsoftgraph/[email protected]/applications/delta/delta_request_builder.go:68:68: cannot use func literal (type func() serialization.Parsable) as type serialization.ParsableFactory in argument to m.requestAdapter.SendCollectionAsync
# github.com/microsoftgraph/msgraph-sdk-go/admin/serviceannouncement/messages/item/attachmentsarchive
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/item/attachmentsarchive/attachments_archive_request_builder.go:96:53: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveAsync
pkg/mod/github.com/microsoftgraph/[email protected]/admin/serviceannouncement/messages/item/attachmentsarchive/attachments_archive_request_builder.go:108:47: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendNoContentAsync
# github.com/microsoftgraph/msgraph-sdk-go/applications/item/checkmembergroups
pkg/mod/github.com/microsoftgraph/[email protected]/applications/item/checkmembergroups/check_member_groups_request_builder.go:70:63: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendPrimitiveCollectionAsync
# github.com/microsoftgraph/msgraph-sdk-go/applications/validateproperties
pkg/mod/github.com/microsoftgraph/[email protected]/applications/validateproperties/validate_properties_request_builder.go:70:47: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to m.requestAdapter.SendNoContentAsync
# github.com/microsoftgraph/msgraph-sdk-go-core
# ... (rest of the output ommited for readability)
root@291304e6afd7:/go# 

Thanks

Compiler error when using msgraphgocore.NewPageIterator

The examples in the Readme and on the microsoft docs (https://docs.microsoft.com/en-us/graph/sdks/paging?tabs=Go) give examples like this for creating a page iterator

pageIterator, err := msgraphcore.NewPageIterator(result, adapter.GraphRequestAdapterBase,
    func() serialization.Parsable {
        return messages.NewMessagesResponse()
    })

However, this results in a compiler error:

cannot use func literal (type func() serialization.Parsable) as type serialization.ParsableFactory in argument to msgraphgocore.NewPageIterator

And the NewPageIterator function is defined like https://github.com/microsoftgraph/msgraph-sdk-go-core/blob/bc08a7c420acc78d4788f3adf0b9ef986f68fe77/page_iterator.go#L49, which takes a ParsableFactory and not a Parsable func. I think this was the commit that changed the interface (microsoftgraph/msgraph-sdk-go-core@63efd75).

func NewPageIterator(res interface{}, reqAdapter GraphRequestAdapterBase, constructorFunc serialization.ParsableFactory) (*PageIterator, error) {

I'm very new to the library, but I can't figure out how to or find a working example of creating a pageIterator. How might I go about doing so? All the examples I've found in the docs generate that error. Here is the example code to reproduce the compiler error (mostly copied from the Readme example in this repository). Thanks for your help!

package main

import (
	"context"
	"fmt"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/microsoft/kiota/abstractions/go/serialization"
	a "github.com/microsoft/kiota/authentication/go/azure"
	msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
	msgraphcore "github.com/microsoftgraph/msgraph-sdk-go-core"
	"github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph"
	users "github.com/microsoftgraph/msgraph-sdk-go/users"
)

func main() {

	cred, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
		TenantID: "<the tenant id from your app registration>",
		ClientID: "<the client id from your app registration>",
		UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error {
			fmt.Println(message.Message)
			return nil
		},
	})

	if err != nil {
		fmt.Printf("Error creating credentials: %v\n", err)
	}

	auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{"Files.Read"})
	if err != nil {
		fmt.Printf("Error authentication provider: %v\n", err)
		return
	}

	adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
	if err != nil {
		fmt.Printf("Error creating adapter: %v\n", err)
		return
	}
	client := msgraphsdk.NewGraphServiceClient(adapter)
	result, err := client.Users().Get(nil)

	if err != nil {
		fmt.Printf("Error getting users: %v\n", err)
	}

	pageIterator, err := msgraphcore.NewPageIterator(result, adapter.GraphRequestAdapterBase,
		func() serialization.Parsable {
			return users.NewUsersResponse()
		})

	err = pageIterator.Iterate(func(pageItem interface{}) bool {
		user := pageItem.(graph.User)
		fmt.Printf("%s\n", *user.GetDisplayName())
		// Return true to continue the iteration
		return true
	})
}

My go.mod file is using the most recent versions of the libraries:

module main.go

go 1.17

require (
	github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.13.2
	github.com/microsoft/kiota/abstractions/go v0.0.0-20220315140630-e2d45e682974
	github.com/microsoft/kiota/authentication/go/azure v0.0.0-20220315140630-e2d45e682974
	github.com/microsoftgraph/msgraph-sdk-go v0.14.0
	github.com/microsoftgraph/msgraph-sdk-go-core v0.0.15
)

require (
	github.com/Azure/azure-sdk-for-go/sdk/azcore v0.21.0 // indirect
	github.com/Azure/azure-sdk-for-go/sdk/internal v0.9.1 // indirect
	github.com/AzureAD/microsoft-authentication-library-for-go v0.4.0 // indirect
	github.com/cjlapao/common-go v0.0.18 // indirect
	github.com/golang-jwt/jwt v3.2.1+incompatible // indirect
	github.com/google/uuid v1.3.0 // indirect
	github.com/kylelemons/godebug v1.1.0 // indirect
	github.com/microsoft/kiota/http/go/nethttp v0.0.0-20220315140630-e2d45e682974 // indirect
	github.com/microsoft/kiota/serialization/go/json v0.0.0-20220315140630-e2d45e682974 // indirect
	github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4 // indirect
	github.com/yosida95/uritemplate/v3 v3.0.1 // indirect
	golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f // indirect
	golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect
	golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect
	golang.org/x/text v0.3.7 // indirect
)

Unable to patch application: invalid memory address or nil pointer dereference

Hi,

I've tried a few different ways to Patch an application, but I cannot get it to work. I'm a bit of a newbie to Go, so apologies if this is something I should've been able to spot. With the code below I am able to successfully retrieve the current Redirect URIs for my application, however I am then unable to Patch the same application. I'm wondering if it's something I'm not doing correctly, any help is very much appreciated.

I've did have a look at some of the previous issues and tried things like go get -u but I've had no luck.

Relevant code:

	graphClient := msgraphsdk.NewGraphServiceClient(adapter)

	//Get application
	app, err := graphClient.ApplicationsById(appId).Get(nil)
	if err != nil {
		fmt.Printf("Problem with getting app: %v\n", err)
	}
	currentRedirectURIS := app.GetWeb().GetRedirectUris()
	fmt.Printf("Current URIs: %s\n", currentRedirectURIS)

	// Patch Application
	requestBody := graph.NewApplication()
	uris := graph.NewWebApplication()
	uris.SetRedirectUris([]string {
		"https://test-app.com",
	})

	requestBody.SetWeb(uris)
	patchOptions := &applications.ApplicationItemRequestBuilderPatchOptions {
		Body: requestBody,
	}
	graphClient.ApplicationsById(appId).Patch(patchOptions)

Output of a build:

Current URIs: [https://test-123.com]
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x139b9d4]

goroutine 1 [running]:
github.com/microsoft/kiota/serialization/go/json.(*JsonSerializationWriter).WriteObjectValue(0xc00033d068, {0x1468e09, 0x3}, {0x0, 0x0})
        /Users/matt/go/pkg/mod/github.com/microsoft/kiota/serialization/go/[email protected]/json_serialization_writer.go:246 +0x34
github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph.(*Application).Serialize(0xc000390280, {0x1511120, 0xc00033d068})
        /Users/matt/go/pkg/mod/github.com/microsoftgraph/[email protected]/models/microsoft/graph/application.go:816 +0xfd
github.com/microsoft/kiota/serialization/go/json.(*JsonSerializationWriter).WriteObjectValue(0xc00033d068, {0x0, 0x0}, {0x1502ff0, 0xc000390280})
        /Users/matt/go/pkg/mod/github.com/microsoft/kiota/serialization/go/[email protected]/json_serialization_writer.go:253 +0x1bf
github.com/microsoft/kiota/abstractions/go.(*RequestInformation).SetContentFromParsable(0xc00033a780, {0x150bc38, 0xc00019a280}, {0x146d402, 0x10}, {0xc000392070, 0x1478145, 0x1})
        /Users/matt/go/pkg/mod/github.com/microsoft/kiota/abstractions/[email protected]/request_information.go:169 +0x153
github.com/microsoftgraph/msgraph-sdk-go/applications/item.(*ApplicationItemRequestBuilder).CreatePatchRequestInformation(0xc000337980, 0xc00011bf38)
        /Users/matt/go/pkg/mod/github.com/microsoftgraph/[email protected]/applications/item/application_item_request_builder.go:156 +0x1b7
github.com/microsoftgraph/msgraph-sdk-go/applications/item.(*ApplicationItemRequestBuilder).Patch(0xc000337980, 0x1478145)
        /Users/matt/go/pkg/mod/github.com/microsoftgraph/[email protected]/applications/item/application_item_request_builder.go:253 +0x25
main.main()
        /Users/matt/workspace/go-projects/repy-url-updater/pkg/testing/main.go:53 +0x4a5

Process finished with the exit code 2

Let me know if there's anything else I can provide to help figure this out. Thanks!

Serialization Method requires clarification

How can SDK be used to write retrieved items?

In the code example: https://docs.microsoft.com/en-gb/graph/sdks/paging?tabs=Go

The snippet highlights how to receive each Message from the Mailbox. Messages are defined [here][]

The SerializationWriter Interface is defined within Kiota abstractions, but it is unclear which how to save a particular message to an app.
Code is adapted from provided code above:

target := "My Message"
// Iterate over all pages (e.g. Messages)
iterateErr := pageIterator.Iterate(func(pageItem interface{}) bool {
    message := pageItem.(models.Messageable)
    fmt.Printf("%s\n", *message.GetSubject())
    if target == *message.GetSubject() {
        entries := message.GetFieldDeserializers(). // MAP Key: <string> Type: func(serialization.ParseNode) error
        for key, value := in range entries{
            // NEED CODE FOR HERE
            val() // NOT VALID     
    // Return true to continue the iteration
    return true
})

How do you get the value out of the value?
Golang produces the following error:

not enough arguments in call to val
        have ()
        want (serialization.ParseNode)

This item can be considered closed when the following items have been completed:

  • Instruction on serialization has been verified
  • Instruction on importing objects has been verified
    Documentation will have to wait until the design team specifies where the code snippets should live.

Unable to create new Application with KeyCredential

I am unable to create a new Application with included KeyCredential due to seeming json serialization issues.

When I dig in with the debugger, I see the returned response from the API:

Expected property 'type_escaped' is not present on resource of type 'KeyCredential'

The following is a sample snippet which I used to repro this issue. Some values will have to be adjusted, of course :)

package main

import (
	"fmt"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	a "github.com/microsoft/kiota/authentication/go/azure"
	msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
	"github.com/microsoftgraph/msgraph-sdk-go/applications"
	"github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph"
	"io/ioutil"
	"log"
)

func main() {
	_, pemBytes := getPEMBytes()
	cert, key, _ := azidentity.ParseCertificates(pemBytes, nil)
	cred, _ := azidentity.NewClientCertificateCredential("my-tenant-id", "my-client-id",
		cert, key, &azidentity.ClientCertificateCredentialOptions{})

	auth, _ := a.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{".default"})
	adapter, _ := msgraphsdk.NewGraphRequestAdapter(auth)
	client := msgraphsdk.NewGraphServiceClient(adapter)

	managedApp := graph.NewApplication()
	n := "my-test-application"
	managedApp.SetDisplayName(&n)

	managedAppKeyCred := graph.NewKeyCredential()
	keyBytes, _ := ioutil.ReadFile("new-app-credential.crt")
	managedAppKeyCred.SetKey(keyBytes)
	managedAppKeyCred.SetDisplayName(&n)
	t := "AsymmetricX509Cert"
	managedAppKeyCred.SetType_escaped(&t)
	u := "Verify"
	managedAppKeyCred.SetUsage(&u)
	managedApp.SetKeyCredentials([]graph.KeyCredential{*managedAppKeyCred})

	options := applications.ApplicationsRequestBuilderPostOptions{
		Body: managedApp,
	}

	result, err := client.Applications().Post(&options)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("yay: %s", *result.GetAppId()) // note that in current state, this panics since the API returns an error but the SDK does not handle it (I'm aware this is a known issue)
}

I have just re-run go get -u and retested and this error persists.

go get -u                                        
go: downloading golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71
go get: upgraded github.com/microsoft/kiota/abstractions/go v0.0.0-20211201125630-3501743a5dc5 => v0.0.0-20211203190524-b3aa0a7d4445
go get: upgraded github.com/microsoft/kiota/http/go/nethttp v0.0.0-20211130101617-a4871ba0f35f => v0.0.0-20211203190524-b3aa0a7d4445
go get: upgraded github.com/microsoft/kiota/serialization/go/json v0.0.0-20211112084539-17ac73ffdc7c => v0.0.0-20211203190524-b3aa0a7d4445
go get: upgraded github.com/microsoftgraph/msgraph-sdk-go-core v0.0.4 => v0.0.5
go get: upgraded github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 => v0.0.0-20210911075715-681adbf594b8
go get: upgraded golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 => v0.0.0-20211202192323-5770296d904e
go get: upgraded golang.org/x/net v0.0.0-20211123203042-d83791d6bcd9 => v0.0.0-20211205041911-012df41ee64c
go get: upgraded golang.org/x/sys v0.0.0-20210423082822-04245dca01da => v0.0.0-20211205182925-97ca703d548d

`go get -u` timing out ๐Ÿ˜ข

I have a relatively empty library which encapsulates/abstracts the azure ad sdk. On my machine, go get -u and go mod tidy time-out after about 5mins during the fetching of dependencies.

To make use of this library, the following dependencies were needed (full go.mod):

module github.com/vigilant-go/azuread

go 1.18

require (
	github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.14.0
	github.com/microsoft/kiota-authentication-azure-go v0.1.0
	github.com/microsoftgraph/msgraph-sdk-go v0.19.0
	github.com/microsoftgraph/msgraph-sdk-go-core v0.22.0
	github.com/pkg/errors v0.9.1
	github.com/stretchr/testify v1.7.1
	github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d
	golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4
)

require (
	github.com/Azure/azure-sdk-for-go/sdk/azcore v0.23.0 // indirect
	github.com/Azure/azure-sdk-for-go/sdk/internal v0.9.1 // indirect
	github.com/AzureAD/microsoft-authentication-library-for-go v0.4.0 // indirect
	github.com/cjlapao/common-go v0.0.19 // indirect
	github.com/davecgh/go-spew v1.1.1 // indirect
	github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
	github.com/google/uuid v1.3.0 // indirect
	github.com/kylelemons/godebug v1.1.0 // indirect
	github.com/microsoft/kiota-abstractions-go v0.4.0 // indirect
	github.com/microsoft/kiota-http-go v0.3.0 // indirect
	github.com/microsoft/kiota-serialization-json-go v0.3.0 // indirect
	github.com/microsoft/kiota-serialization-text-go v0.2.0 // indirect
	github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
	golang.org/x/net v0.0.0-20220420153159-1850ba15e1be // indirect
	golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect
	golang.org/x/text v0.3.7 // indirect
	gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)

It's not related to my machine, as this even happens on GitHub Actions (every time):

name: Build and Test
on: [push, pull_request]
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:

      - name: Set up Go 1.18
        uses: actions/setup-go@v2
        with:
          go-version: 1.18

      - name: Check out source code
        uses: actions/checkout@v2

      - name: Build
        run: go build .

      - name: Test
        run: go test -v ./...

6ms to fetch dependencies ๐Ÿ˜ข :

Screenshot 2022-04-22 at 09 02 56

This started happening yesterday if that helps?

Query parameter does not work properly when retrieving users

Hi

I have created a sample program to retrieve a user, but the query parameter does not seem to be working correctly.
When I debug it, it seems that the query parameter is not set correctly, is it still a limitation?

The following sample query for the CreatedDateTime property to be included in the response, but returns NULL.

func getUser(client *msgraphsdk.GraphServiceClient, id string) {

	options := &usersitem.UserRequestBuilderGetOptions{
		Q: &usersitem.UserRequestBuilderGetQueryParameters{
			Select_escaped: []string{"createdDateTime"},
		},
	}
	result, err := client.UsersById(id).Get(options)
	if err != nil {
		fmt.Printf("Error get user : %v\n", err)
		return
	}

	fmt.Printf("result.GetDisplayName(): %v\n",result.GetDisplayName())
	fmt.Printf("result.GetCreatedDateTime(): %v\n", result.GetCreatedDateTime())
}

Thanks.

Convert DirectoryObjects to User objects?

Hi, I am using the GO SDK to fetch users and group information from AD. Because I have a lot of users, I am fetching groups first and then foreach group I get it's members.

func fetchGroupMembers(*groups graph.Group) {
	var dirObjList []graph.DirectoryObject = make([]graph.DirectoryObject, 0)
	
	for _, group := range groups {
		page1, err := client.GroupsById(*group.GetId()).Members().Get(nil)
		if err != nil {
			return err
		}
		dirObjList = append(dirObjList, page1.GetValue()...)

		//Iterator to iterate over remaining pages and fetch users
		iterator, err := msgcore.NewPageIterator(page1, *adapter, func() serialization.Parsable {
			return directoryobjects.NewDirectoryObjectsResponse()
		})
		if err != nil {
			return err
		}
		callback := func(item interface{}) bool {
			dirObjList = append(dirObjList, item.(graph.DirectoryObject))
			return true
		}
		iterator.Iterate(callback)
		fmt.Println("#Users: ", len(dirObjList))

		//Here, I am expecting users object but I get directory objects
		for _, u := range dirObjList {

			//I need to access user object attributes like displayName and so on ...
		}

		match = false
	}
}

Is there a way to convert graph.DirectoryObjects to graph.User objects? Or how should I go about this? Thanks.
PS: This code is representational only.

filter query param not being added to the request

Trying to filter applications based on displayName and I see the filter value is not being honored. This is the sample function:

func (c *client) GetApplication(ctx context.Context, displayName string) (*graph.Application, error) {
	appGetOptions := &applications.ApplicationsRequestBuilderGetOptions{
		Q: &applications.ApplicationsRequestBuilderGetQueryParameters{
			Filter: to.StringPtr(getDisplayNameFilter(displayName)),
		},
	}

	resp, err := client.Applications().Get(appGetOptions)
	if err != nil {
		return nil, err
	}
	if len(resp.GetValue()) == 0 {
		return nil, errors.Errorf("application with display name '%s' not found", displayName)
	}
	return &resp.GetValue()[0], nil
}

func getDisplayNameFilter(displayName string) string {
	return fmt.Sprintf("startswith(displayName, '%s')", displayName)
}

The response contains all the applications in my tenant. Tried to debug this a little more and found AddQueryParameters isn't actually adding the query parameters to the request info.

How do I get the delegated API permissions for an application from the graph API?

I'm not able to figure out how to use the API to retrieve the api permissions assigned to my application. This is the page of permissions I want to retrieve via the graph api. I'm using the API listed here: https://docs.microsoft.com/en-us/graph/api/serviceprincipal-list-delegatedpermissionclassifications?view=graph-rest-1.0&tabs=http. However, it doesn't seem to return any delegated permissions. The error is probably on my end, and I'm likely using the wrong API. Would someone be able to point me in the right direction for retrieving the "API Permissions" through the graph api? Thanks!

// setup client *msgraphsdk.GraphServiceClient (clipped for brevity)
permissions, er := client.ServicePrincipalsById(id).DelegatedPermissionClassifications().Get(nil)
if er != nil {
	fmt.Printf("error: %s %v\n", er, permissions)
	return er
}

piterator, er := msgraphcore.NewPageIterator(permissions, adapter.GraphRequestAdapterBase, graph.CreateDelegatedPermissionClassificationCollectionResponseFromDiscriminatorValue)
if er != nil {
	fmt.Printf("error: %s %v\n", er, permissions)
	return er
}

er = piterator.Iterate(func(pageItem interface{}) bool {
	p := pageItem.(*graph.DelegatedPermissionClassification)
	fmt.Printf("permission grant for id: %s -> %s %s\n", foundId, *p.GetId(), *p.GetPermissionName())
	return true
})

permissions-2

Query Parameters are not working due to missing $ prefix in logic

As mentioned in #114, AddQueryParameters which sets the $search, $expand, $top, $skip etc. in github.com/microsoft/[email protected]/request_information.go is using reflection to name the parameters which you are adding to your URLs in all API calls (e.g. (m *UsersRequestBuilder) CreateGetRequestInformation(options *UsersRequestBuilderGetOptions)).

Unfortunately you need to inject some additional logic as the MS Graph query parameters require the $ ODATA prefix.

This means no API calls work as soon as you supply query parameters (so no paging, no filtering, no field fetching) otherwise you get an error like:

Request_BadRequest: Unrecognized query argument specified: 'top,skip'.: error status code received from the API

I believe you should be able to fix this inside this library - the logic in microsoft/kiota-abstractions-go isn't wrong, you just can't use the final results in this library because of MS graph API / OData requirements for the $ prefix.

Failing to query for report

Hi,

I wanted to test if I could use this library for one usecase and stumbled over an error.
After debugging it seems that the uri-template parser does not like the character ' which is present in the URI.

URI is set here and looks like this
"{+baseurl}/reports/microsoft.graph.getOffice365ActiveUserDetail(period='{period}')"

Template parsing happens here

The error I get is this one
Error getting the report: uritemplate:72:invalid literals

Code

func GetReport() {
	//auth
	cred, err := azidentity.NewClientSecretCredential(
		"x",
		"x",
		"x",
		nil,
	)

	if err != nil {
		fmt.Printf("Error creating credentials: %v\n", err)
	}

	auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{".default"})
	if err != nil {
		fmt.Printf("Error authentication provider: %v\n", err)
		return
	}

	adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
	if err != nil {
		fmt.Printf("Error creating adapter: %v\n", err)
		return
	}
	client := msgraphsdk.NewGraphServiceClient(adapter)


	period := "D7"
	result, err := client.Reports().GetOffice365ActiveUserDetailWithPeriod(&period).Get(nil)
	if err != nil {
		fmt.Printf("Error getting the report: %s\n", err)
		return
	}
	fmt.Printf("Found Drive : %v\n", result.GetContent())
}

BR
Henry

Query Parameters missing in CalendarViewRequest

In CalendarViewRequest the StartDateTime and EndDateTime are not sent with the Get-Request.
When trying to use the function, it just returns an empty slice and nil error. But when i intercept the request, i see that the paramenters are not sent with the request and the following error has been returned by the api:
This request requires a time window specified by the query string parameters StartDateTime and EndDateTime.
Happens with latest version (v0.3.1) with all deps up-to-date as well.
Similar to #17
Sample Code:

afterf := "2021-12-01T00:00:00+02:00"
untilf := "2021-12-31T00:00:00+02:00"
opts := &calendarview.CalendarViewRequestBuilderGetOptions{
	Q: &calendarview.CalendarViewRequestBuilderGetQueryParameters{
		StartDateTime: &afterf,
		EndDateTime: &untilf,
	},
}
result, err := s.graph.UsersById(id).CalendarView().Get(opts)
// result = []
// err = nil

Unable to query Groups fatal invalid memory address

Thanks for the active support on this sdk.
I've been trying to query the groups endpoint but getting a fatal error:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x10be594]

goroutine 1 [running]:
io.ReadAll({0x0, 0x0})
	/usr/local/Cellar/go/1.17.3/libexec/src/io/io.go:633 +0xd4
io/ioutil.ReadAll(...)
	/usr/local/Cellar/go/1.17.3/libexec/src/io/ioutil/ioutil.go:27
github.com/microsoft/kiota/http/go/nethttp.(*CompressionHandler).Intercept(0xc00020e068, {0x16fa0a0, 0xc000208a50}, 0x15df740, 0xc000212300)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/compression_handler.go:69 +0x12a
github.com/microsoft/kiota/http/go/nethttp.(*middlewarePipeline).Next(0x8, 0x29005b8, 0x10)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/pipeline.go:36 +0x52
github.com/microsoft/kiota/http/go/nethttp.RedirectHandler.Intercept({{0x1666710, 0x5}}, {0x16fa0a0, 0xc000208a50}, 0xc000062d80, 0xc000212300)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/redirect_handler.go:83 +0xb4
github.com/microsoft/kiota/http/go/nethttp.(*middlewarePipeline).Next(0x0, 0x0, 0x0)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/pipeline.go:36 +0x52
github.com/microsoft/kiota/http/go/nethttp.RetryHandler.Intercept({{0x1666708, 0x0, 0x0}}, {0x16fa0a0, 0xc000208a50}, 0x104e934, 0xc000212300)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/retry_handler.go:99 +0xcb
github.com/microsoft/kiota/http/go/nethttp.(*middlewarePipeline).Next(0xc00021c500, 0x16f1600, 0x1)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/pipeline.go:36 +0x52
github.com/microsoftgraph/msgraph-sdk-go-core.GraphODataQueryHandler.Intercept({0xc00021c500, {0x1666718}}, {0x16fa0a0, 0xc000208a50}, 0xf64feb8019465d01, 0xc000212300)
	/Users/user/go/pkg/mod/github.com/microsoftgraph/[email protected]/graph_odata_query_handler.go:63 +0x1d4
github.com/microsoft/kiota/http/go/nethttp.(*middlewarePipeline).Next(0x1576de0, 0x0, 0xc00016f500)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/pipeline.go:36 +0x52
github.com/microsoftgraph/msgraph-sdk-go-core.GraphTelemetryHandler.Intercept({{0xc000242000, 0x0}}, {0x16fa0a0, 0xc000208a50}, 0xc0004da580, 0xc000212300)
	/Users/user/go/pkg/mod/github.com/microsoftgraph/[email protected]/graph_telemetry_handler.go:49 +0x209
github.com/microsoft/kiota/http/go/nethttp.(*middlewarePipeline).Next(0x0, 0x0, 0x0)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/pipeline.go:36 +0x52
github.com/microsoft/kiota/http/go/nethttp.(*customTransport).RoundTrip(0x30, 0x16fa080)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/pipeline.go:44 +0x1e
net/http.send(0xc000212300, {0x16fa080, 0xc00020c068}, {0x1621a80, 0x1, 0x0})
	/usr/local/Cellar/go/1.17.3/libexec/src/net/http/client.go:252 +0x5d8
net/http.(*Client).send(0x1c37900, 0xc000212300, {0x1643f61, 0xd, 0x0})
	/usr/local/Cellar/go/1.17.3/libexec/src/net/http/client.go:176 +0x9b
net/http.(*Client).do(0x1c37900, 0xc000212300)
	/usr/local/Cellar/go/1.17.3/libexec/src/net/http/client.go:725 +0x908
net/http.(*Client).Do(...)
	/usr/local/Cellar/go/1.17.3/libexec/src/net/http/client.go:593
github.com/microsoft/kiota/http/go/nethttp.(*NetHttpRequestAdapter).getHttpResponseMessage(0xc00021a320, {0x0, 0x0, 0xc000208b40, 0xc000208b70, {0x0, 0x0, 0x0}, 0xc000208ae0, {0x16574d6, ...}, ...})
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/nethttp_request_adapter.go:100 +0x175
github.com/microsoft/kiota/http/go/nethttp.(*NetHttpRequestAdapter).SendAsync(0xc00021a320, {0x0, 0x0, 0xc000208b40, 0xc000208b70, {0x0, 0x0, 0x0}, 0xc000208ae0, {0x16574d6, ...}, ...}, ...)
	/Users/user/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/nethttp_request_adapter.go:142 +0x78
github.com/microsoftgraph/msgraph-sdk-go/groups/item.(*GroupRequestBuilder).Get(0xc000208b10, 0x1652d7d)
	/Users/user/go/pkg/mod/github.com/microsoftgraph/[email protected]/groups/item/group_request_builder.go:312 +0xbe
main.main()
	/Users/user/go/src/graph-api/main.go:59 +0x2bd
exit status 2

This is the code I'm trying out and it also happens to the commented Me endpoint. Not sure if I'm doing something wrong here. The dependencies seem to be all updated, and it seems like things go bad in the result line. Did some debugging and authentication piece gets the token, but it fails on the actual request.

package main

import (
	"context"
	"fmt"

	azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	a "github.com/microsoft/kiota/authentication/go/azure"
	msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
)

func main() {
	cred, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
		TenantID: "my-tenant-id",
		ClientID: "my-svc-principal-id",
		UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error {
			fmt.Println(message.Message)
			return nil
		},
	})
	if err != nil {
		fmt.Printf("Error creating credentials: %v\n", err)
	}

	auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{"Directory.Read.All"})
	if err != nil {
		fmt.Printf("Error authentication provider: %v\n", err)
		return
	}

	adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
	if err != nil {
		fmt.Printf("Error creating adapter: %v\n", err)
		return
	}

	client := msgraphsdk.NewGraphServiceClient(adapter)

	//result, err := client.Me().Get(nil)
	result, err := client.GroupsById("my-group-id").Get(nil)

	if err != nil {
		fmt.Printf("Error getting the group: %v\n", err)
	}

	fmt.Printf("Group detail: %v\n", result)
}

Extra headers added via round tripper break oauth2 exchange requests

I've spent a couple of days debugging my oauth2 issue only to find out that msgraph sdk implements a round tripper that adds extra headers that eventually break oauth2 exchange request. The round tripper calls middlewares including the compression handler from microsoft/kiota that adds Content-Encoding: gzip header that breaks oauth2 requests.

I'm not quite sure how exactly round tripper registration works but after calling these lines all of my subsequent oauth2 request break:

import (
	a "github.com/microsoft/kiota/authentication/go/azure"
	msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
)

auth, _ := a.NewAzureIdentityAuthenticationProvider(cred)
adapter, _ := msgraphsdk.NewGraphRequestAdapter(auth)

Cannot paginate through users collection

Encountered on msgraph-sdk-go v0.15.0 when attempting to support client-side pagination in a service using the SDK.

It is unclear how to paginate through the users collection using the SDK. UsersRequestBuilderGetQueryParameters takes an integer Skip value but according to the docs this is not supported. If I supply $top then a nextLink is returned but I cannot see a way to supply a skipToken query parameter.

Loving the SDK so far, but unsure how to progress on this one!

Example code for fetching emails with all header and attachment contents

Hello,

Unfortunately I found the documentation and overall code really hard to work with. Even the installation of libraries causes performance spikes and general layout is too confusing.

I could not figure out a way to efficiently fetch emails with all headers and attachment (content included). Currently I'm able to fetch emails with header but only info I get on attachments are size and ID.

Could you kindly include example of how attachments of emails (content) can be retrieved?

Example code I've been working on:

package main

import (
	"fmt"

	azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/microsoft/kiota/abstractions/go/serialization"
	a "github.com/microsoft/kiota/authentication/go/azure"
	msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
	msgraphcore "github.com/microsoftgraph/msgraph-sdk-go-core"
	"github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph"
	"github.com/microsoftgraph/msgraph-sdk-go/users/item/mailfolders/item/messages"

	//"github.com/microsoftgraph/msgraph-sdk-go/users/item/mailfolders/item/messages/item/attachments"
	attc "github.com/microsoftgraph/msgraph-sdk-go/users/item/mailfolders/item/messages/item/attachments/item"
)

func main() {
	tenantID := "REDACTED"
	clientID := "REDACTED"
	secretVal := "REDACTED"
	//secretID := "REDACTED"

	cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secretVal, nil)

	if err != nil {
		fmt.Printf("Error creating credentials: %v\n", err)
	}

	auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{".default"})
	if err != nil {
		fmt.Printf("Error authentication provider: %v\n", err)
		return
	}

	adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
	if err != nil {
		fmt.Printf("Error creating adapter: %v\n", err)
		return
	}
	client := msgraphsdk.NewGraphServiceClient(adapter)

	filter := "IsRead eq false"
	expand := []string{"singleValueExtendedProperties($filter=id eq 'String 0x007D')", "attachments"}
	selectParam := []string{"id", "subject", "receivedDateTime", "sentDateTime", "from", "toRecipients", "ccRecipients", "bccRecipients", "replyTo", "internetMessageHeaders", "singleValueExtendedProperties", "body", "hasAttachments", "sender"}
	requestParameters := &messages.MessagesRequestBuilderGetQueryParameters{
		Filter: &filter,
		Expand: expand,
		Select: selectParam,
	}
	options := messages.MessagesRequestBuilderGetOptions{
		Q: requestParameters,
	}

	response, err := client.UsersById("REDACTED").MailFoldersById("Inbox").Messages().Get(&options)
	if err != nil {
		fmt.Printf("Error getting mails: %v\n", err)
	}
	if response == nil {
		fmt.Printf("Response nil")
		return
	}
	pageIterator, err := msgraphcore.NewPageIterator(response, adapter.GraphRequestAdapterBase,
		func() serialization.Parsable {
			return messages.NewMessagesResponse()
		})

	err = pageIterator.Iterate(func(pageItem interface{}) bool {
		message := pageItem.(graph.Message)
		fmt.Printf("Message at %v: %v\n", *(message.GetReceivedDateTime()), *(message.GetSubject()))
		fmt.Printf("Message %v\n", *(message.GetBody().GetContent()))
		for _, attachment := range message.GetAttachments() {
			expand := []string{"microsoft.graph.itemattachment/item"}
			requestParametersAttc := &attc.AttachmentRequestBuilderGetQueryParameters{
				Expand: expand,
			}
			optionsAttc := attc.AttachmentRequestBuilderGetOptions{
				Q: requestParametersAttc,
			}

			response, err := client.UsersById("REDACTED").MailFoldersById("Inbox").MessagesById(*message.GetId()).AttachmentsById(*attachment.GetId()).Get(&optionsAttc)
			if err != nil {
				fmt.Printf("Error getting attachment: %v\n", err)
			}
			fmt.Printf("attachment: %v\n", response.GetContentType())

		}
		return true
	})

}

querying ServicePrincipals with a filter

I've been kicking the tires with this new (new to me) graph package, and I've managed to get some bits working, but I'm failing to be able to list ServicePrincipals with filters defined. Following the same pattern I used for creating an Application, when I try it with a ServicePrincipal I get no results (and an error if you dig into the actual response variable returned).

func ensureAppRegistrationExists(name string) (*graph.Application, error) {
	filter := fmt.Sprintf("displayname eq '%s'", name)
	listQuery := &applications.ApplicationsRequestBuilderGetOptions{
		Q: &applications.ApplicationsRequestBuilderGetQueryParameters{
			Filter: &filter,
		},
	}

	resp, err := graphClient.Applications().Get(listQuery)
	if err != nil {
		log.Fatalf("Error listing Apps: %+v\n", err)
	}

	switch len(resp.GetValue()) {
	case 0:
		log.Printf("No existing App found, will create one...")
		newApp := graph.NewApplication()
		newApp.SetDisplayName(&name)
		postOpts := &applications.ApplicationsRequestBuilderPostOptions{
			Body: newApp,
		}

		app, err := graphClient.Applications().Post(postOpts)
		if err != nil {
			log.Fatalf("Error creating app: %+v\n", err)
		}
		fmt.Printf("Created App: %+v\n", *app.GetAppId())
		return app, nil
	case 1:
		app := resp.GetValue()[0]
		log.Printf("Found single App with displayname %s: %s", name, *app.GetAppId())
		return &app, nil
	default:
		for _, app := range resp.GetValue() {
			fmt.Printf("APP: %+v\tNAME: %+v\n", *app.GetAppId(), *app.GetDisplayName())
		}
		return nil, fmt.Errorf("unexpect number of apps found: %d", len(resp.GetValue()))
	}
}

func ensureServicePricipalExists(name string) error {
	appReg, err := ensureAppRegistrationExists(name)
	if err != nil {
		log.Fatalf("FAIL :%+v\n", err)
	}

	filter := fmt.Sprintf("appId eq '%s'", *appReg.GetAppId())
	listQuery := &serviceprincipals.ServicePrincipalsRequestBuilderGetOptions{
		Q: &serviceprincipals.ServicePrincipalsRequestBuilderGetQueryParameters{
			Filter: &filter,
		},
	}
	resp, err := graphClient.ServicePrincipals().Get(listQuery)
	if err != nil {
		log.Fatalf("failed to list ServicePrincipals: %+v\n", err)
	}

	switch len(resp.GetValue()) {
	case 0:
		newSP := graph.NewServicePrincipal()
		newSP.SetAppId(appReg.GetAppId())
		newSP.SetDisplayName(appReg.GetDisplayName())
		query := &serviceprincipals.ServicePrincipalsRequestBuilderPostOptions{
			Body: newSP,
		}
		sp, err := graphClient.ServicePrincipals().Post(query)
		if err != nil {
			log.Fatalf("fialed to create SP: %+v\n", err)
		}
		fmt.Printf("Created new SesrvicePrincipal: %+v\n", sp)
		return nil
	case 1:
		sp := resp.GetValue()[0]
		log.Printf("Found single ServicePrincipal with displayname %s: %s", *sp.GetDisplayName(), *sp.GetAppId())
		return nil
	default:
		return fmt.Errorf("Unexpected number of serviceprincipals found: %d", len(resp.GetValue()))

	}
}

When digging into the resp variable returned from the ServicePrincipals().Get(), I see an error code of Request_BadRequest and a more detailed message of "Unrecognized query argument specified: 'filter'."

Because there is no error returned, it just tries to re-create a new ServicePrincipal, and that also doesn't error, but the HTTP response is a 4xx b/c the ServicePrincipal already exists from previous runs through this code.

Based on my reading of the Service Principal section of https://docs.microsoft.com/en-us/graph/aad-advanced-queries , I believe that a query of appId eq '<VALUE>' should "just work".

I stepped down through the raw http.Request that gets built by the graphsdk, and it all appears correct to my eyes.

Here are the versions of the modules I'm currently using:

[jdiaz@minigoomba test (master *)]$ cat go.mod | grep -E 'graph-sdk|kiota'
        github.com/microsoft/kiota/authentication/go/azure v0.0.0-20211130101617-a4871ba0f35f
        github.com/microsoftgraph/msgraph-sdk-go v0.3.0
        github.com/microsoft/kiota/abstractions/go v0.0.0-20211129093841-858bd540489b // indirect
        github.com/microsoft/kiota/http/go/nethttp v0.0.0-20211112084539-17ac73ffdc7c // indirect
        github.com/microsoft/kiota/serialization/go/json v0.0.0-20211112084539-17ac73ffdc7c // indirect
        github.com/microsoftgraph/msgraph-sdk-go-core v0.0.2 // indirect
replace github.com/microsoft/kiota/http/go/nethttp => github.com/microsoft/kiota/http/go/nethttp v0.0.0-20211130101617-a4871ba0f35f

Have I messed something up, or is there something in the graphsdk (or its dependencies) that is keeping this from working?

Unable to create new user

I'm trying to create new user in Azure AD B2C with the following program, but I cannot create it.

        client := msgraphsdk.NewGraphServiceClient(adapter)

	uid := uuid.New().String()
	upn := uid + "@xxxxxx.onmicrosoft.com"
	user := graph.NewUser()
	user.SetId(&uid)
	user.SetDisplayName(ref("Shohei Ohtani"))
	user.SetUserPrincipalName(&upn)
	user.SetMailNickname(&upn)

	d := &u.UsersRequestBuilderPostOptions{
		Body: user,
		H: map[string]string{
			"Content-type": "application/json",
		},
	}
	result, err := client.Users().Post(d)

	if err != nil {
		fmt.Printf("Error create new user %v\n", err)
		return
	}
	spew.Dump(result)

The err is null, so it is not determined to be a direct error, but when I dump the result object, the error message is embedded. Is the program wrong? How can I create the correct user?

Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.

(*graph.User)(0xc0000a4700)({
 DirectoryObject: (graph.DirectoryObject) {
  Entity: (graph.Entity) {
   additionalData: (map[string]interface {}) (len=1) {
    (string) (len=5) "error": (map[string]*jsonserialization.JsonParseNode) (len=3) {
     (string) (len=4) "code": (*jsonserialization.JsonParseNode)(0xc0001205d0)({
      value: (*string)(0xc0001205c0)((len=10) "BadRequest")
     }),
     (string) (len=7) "message": (*jsonserialization.JsonParseNode)(0xc000120630)({
      value: (*string)(0xc000120620)((len=114) "Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.")
     }),
     (string) (len=10) "innerError": (*jsonserialization.JsonParseNode)(0xc000120780)({
      value: (map[string]*jsonserialization.JsonParseNode) (len=3) {
       (string) (len=4) "date": (*jsonserialization.JsonParseNode)(0xc0001206b0)({
        value: (*string)(0xc0001206a0)((len=19) "2021-12-07T01:16:05")
       }),
       (string) (len=10) "request-id": (*jsonserialization.JsonParseNode)(0xc000120710)({
        value: (*string)(0xc000120700)((len=36) "4b689739-151b-4f11-8da2-63a3919bb52e")
       }),
       (string) (len=17) "client-request-id": (*jsonserialization.JsonParseNode)(0xc000120770)({
        value: (*string)(0xc000120760)((len=36) "2a786207-25ef-4694-acc2-70c2d2c59b38")
       })
      }
     })
    }
   },
   id: (*string)(<nil>)
  },
  deletedDateTime: (*time.Time)(<nil>)
 },

Thank

Only first page of results in available when using any api

When using client.Users().Get(), it only gives the first 100 results. GetNextLink() returns the url for retrieving the next set of results but there doesn't seems to be any way of passing that url back into the client.Users().Get() or any other api.

Alternatively, when trying to pass Top or Skip options to the client.Users().Get(options), the request fails with error 400. "The query specified in the URI is not valid. The requested resource is not a collection. Query options $filter, $orderby, $count, $skip, and $top can be applied only on collections."

value is not a collection when trying to client.DirectoryObjects().GetByIds().Post(&opts)

I'm trying to switch from azuread.graph (azure-sdk-for-go) to microsoft.graph but client.DirectoryObjects().GetByIds().Post() fails with an value is not a collection error.

i guess i'm doing something wrong?!
I have a list of principals IDs which i'm trying to translate with an application id (non interative user)

	cred, err := azidentity.NewEnvironmentCredential(nil)
	if err != nil {
		panic(err)
	}

	auth, err := a.NewAzureIdentityAuthenticationProvider(cred)
	if err != nil {
		panic(err)
	}

	adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
	if err != nil {
		panic(err)
	}

	client := msgraphsdk.NewGraphServiceClient(adapter)

	opts := getbyids.GetByIdsRequestBuilderPostOptions{
		Body: getbyids.NewGetByIdsRequestBody(),
	}
	opts.Body.SetIds([]string{....})

	result, err := client.DirectoryObjects().GetByIds().Post(&opts)
	if err != nil {
		panic(err)
	}

Issue creating new user

Context


I'm trying to follow the user docs on creating a new user Link

Code

import (
	"fmt"

	msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
	models "github.com/microsoftgraph/msgraph-sdk-go/models"
	users "github.com/microsoftgraph/msgraph-sdk-go/users"
)


func NewUser(c *msgraphsdk.GraphServiceClient) {

	requestBody := models.NewUser()
	passProfile := models.NewPasswordProfile()
	requestBody.SetPasswordProfile(passProfile)
}

Getting an error specifically with
requestBody.SetPasswordProfile(passProfile)

cannot use passProfile (variable of type *models.PasswordProfile) as models.PasswordProfileable value in argument to requestBody.SetPasswordProfile: *models.PasswordProfile does not implement models.PasswordProfileable (wrong type for method GetFieldDeserializers)
		have GetFieldDeserializers() map[string]func(interface{}, serialization.ParseNode) error
		want GetFieldDeserializers() map[string]func(serialization.ParseNode) errorcompiler

Issue

Based on the docs I expected that the value returned from models.NewPasswordProfile() would match the value that SetPasswordProfile is expecting

I'm a bit new to Golang so sorry in advance if this is just me missing something obvious.
Really excited to start using this SDK

Receiving error when attempting simple request

I am attempting to leverage the library and have not been successful retrieving content from the Graph API

package main

import (
	"fmt"

	azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	a "github.com/microsoft/kiota/authentication/go/azure"
	msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
)

	cred, err := azidentity.NewClientSecretCredential(
		"<TENANT_ID>",
		"<CLIENT_ID>",
		"<CLIENT_SECRET>",
		nil)

	auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(cred)

	if err != nil {
		panic(err)
	}

	adapter, err := msgraphsdk.NewGraphRequestAdapter(auth, , []string{})
	if err != nil {
		panic(err)
	}

	client := msgraphsdk.NewGraphServiceClient(adapter)

	_, err = client.Me().Get(nil)

	if err != nil {
		fmt.Println(err)
	}

All attempts have resulted in the following error

error status code received from the API

Failed to get user with the graph service client

I'm trying to get user with the graph service client:

import (
	"bytes"
	"encoding/json"
	"fmt"

	azure "github.com/microsoft/kiota/authentication/go/azure"
	msgraphsdkgo "github.com/microsoftgraph/msgraph-sdk-go"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

cred, _ := azidentity.NewClientSecretCredential(
		"<my-tenant-id>",
		"<my-client-id>",
		"<my-client-secret>",
		&azidentity.ClientSecretCredentialOptions{
			AuthorityHost: azidentity.AzureChina,
		})

auth, _ := azure.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{
	"https://microsoftgraph.chinacloudapi.cn/.default",
})


adapter, _ := msgraphsdkgo.NewGraphRequestAdapter(auth)

client := msgraphsdkgo.NewGraphServiceClient(adapter)
users, _ := client.Users().Get(nil)
fmt.Println(users)

it got nil:

<nil>

but the config worked when I user Postman:
image

So I read code and see in msgraphsdkgo.NewGraphServiceClient:
image
it's https://microsoftgraph.chinacloudapi.cn/v1.0 for Azure AD of China, and it seems that I can't change this value:
image

Thanks for your attention.

Failed to add license for User Account

Hi, I did want to add a license for user account which has no any license by using AssignLicense:

license := graph.AssignedLicense{}
license.SetSkuId(&skuID)
licenseBody := assignlicense.AssignLicenseRequestBody{}
licenseBody.SetAddLicenses([]graph.AssignedLicense{
	license,
})
licenseBody.SetRemoveLicenses([]string{})

resp, err := client.UsersById("userid").
	AssignLicense().Post(&assignlicense.AssignLicenseRequestBuilderPostOptions{
	Body: &licenseBody,
})
if err != nil {
	fmt.Println(err.Error())
	return err
}

I got an error:

One or more parameters of the function import 'assignLicense' are missing from the request payload. The missing parameters are: removeLicenses.

But it's successful when I use Postman, and this account is correct to get license :

{
    "@odata.context": "https://microsoftgraph.chinacloudapi.cn/v1.0/$metadata#users/$entity",
    "businessPhones": [],
    "displayName": "xxx",
    "givenName": "xxx",
    "jobTitle": null,
    "mail": "xxxx",
    "mobilePhone": null,
    "officeLocation": null,
    "preferredLanguage": null,
    "surname": "xxx",
    "userPrincipalName": "xxxx",
    "id": "userid"
}

I wonder how could I make a correct request with graph sdk. Could you please help me with this?
Sincerely

There is no way to list items in the drive

It seems like there's currently no way of actually listing drive items.
Requests like: GET /me/drive/root/children or GET /drives/{drive-id}/items/{item-id}/children are not possible using this sdk it seems.

I would expect to be able to do something like
client.Me().Drive().Root().Children().Get(nil)

Am I missing something or is this just not possible? Also it seems that it's possible to construct invalid requests as in doing GET /drive/items and it just fails silently.

Query parameters not populating request

Hi!

I've been trying out this module and it seems like there's something wrong when following your examples.

I've tried the following:

func run() error {
	cred, err := azidentity.NewAzureCLICredential(&azidentity.AzureCLICredentialOptions{})
	if err != nil {
		return fmt.Errorf("error creating credentials: %w", err)
	}

	auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{"https://graph.microsoft.com"})
	if err != nil {
		return fmt.Errorf("error authentication provider: %w", err)
	}

	adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
	if err != nil {
		return fmt.Errorf("error creating adapter: %w", err)
	}

	client := msgraphsdk.NewGraphServiceClient(adapter)

	startDateTime := "2021-12-12T20:57:37.046Z"
	endDateTime := "2021-12-19T20:57:37.046Z"

	query := calendarview.CalendarViewRequestBuilderGetQueryParameters{
		StartDateTime: &startDateTime,
		EndDateTime:   &endDateTime,
	}

	options := calendarview.CalendarViewRequestBuilderGetOptions{
		Q: &query,
	}

	result, err := client.Me().CalendarView().Get(&options)
	if err != nil {
		return fmt.Errorf("get req failed: %w", err)
	}

	for _, event := range result.GetValue() {
		subject := event.GetSubject()
		startTime := event.GetStart()
		endTime := event.GetEnd()
		fmt.Printf("%s (%s - %s)\n", *subject, *startTime.GetDateTime(), *endTime.GetDateTime())
	}

	return nil
}

This causes no errors and no results (GetValue() is empty). Digging down deeper into when the request is sent using the debugger, I can see that the query parameters are never populated. I can also see that the body returned by the graph api is:
"{\"error\":{\"code\":\"ErrorInvalidParameter\",\"message\":\"This request requires a time window specified by the query string parameters StartDateTime and EndDateTime.\"}}"

Not sure exactly which of all the modules involved in this actually causing the issue, but I'll start here and please point me in the right direction if you don't think it can be solved from here.

way to get json response

Hi,

Is there any way to get the raw JSON response for an object like applications, users, groups, drive items etc.,

Error adding filter query param to applications request

AddQueryParameters fails with the following error:

INFO[0000] Getting application with display name=azwi-e2e-app-b886 filter=startswith(displayName, 'azwi-e2e-app-b886') 
panic: reflect: NumField of non-struct type *applications.ApplicationsRequestBuilderGetQueryParameters

goroutine 1 [running]:
reflect.(*rtype).NumField(0x0)
        /usr/local/go/src/reflect/type.go:1015 +0x66
github.com/microsoft/kiota/abstractions/go.(*RequestInformation).AddQueryParameters(0xc0000bc720, {0x6b3c20, 0xc0001d70a0})
        /home/anramase/go/pkg/mod/github.com/microsoft/kiota/abstractions/[email protected]/request_information.go:201 +0x131
github.com/microsoftgraph/msgraph-beta-sdk-go/applications.(*ApplicationsRequestBuilder).CreateGetRequestInformation(0xc0004b4420, 0xc00011fcb8)
        /home/anramase/go/pkg/mod/github.com/microsoftgraph/[email protected]/applications/applications_request_builder.go:97 +0x153
github.com/microsoftgraph/msgraph-beta-sdk-go/applications.(*ApplicationsRequestBuilder).Get(0xc0004b4420, 0x79f888)
        /home/anramase/go/pkg/mod/github.com/microsoftgraph/[email protected]/applications/applications_request_builder.go:138 +0x33
github.com/aramase/graphsdk/pkg/cloud.(*AzureClient).GetApplication(0xc00018a700, {0x10, 0x733b72}, {0x72c380, 0x11})
        /home/anramase/go/src/github.com/aramase/graphsdk/pkg/cloud/graph.go:69 +0x225
main.main()
        /home/anramase/go/src/github.com/aramase/graphsdk/cmd/sample/main.go:32 +0x166

Follow up issue to #17
cc @baywet

fatal error: concurrent map writes

Hi,

I'm getting a fatal error fatal error: concurrent map writes. (Stacktrace below) when creating multiple clients.
I'll check if I mutexes or sync.once can help, and update.

goroutine 873 [running]:
runtime.throw({0x1cbe360, 0x4739268})
/usr/local/Cellar/go/1.17.5/libexec/src/runtime/panic.go:1198 +0x71 fp=0xc000979ba8 sp=0xc000979b78 pc=0x1036991
runtime.mapassign_faststr(0x1b4c020, 0xc0001ba7e0, {0x1cb7f79, 0x10})
/usr/local/Cellar/go/1.17.5/libexec/src/runtime/map_faststr.go:294 +0x38b fp=0xc000979c10 sp=0xc000979ba8 pc=0x10143cb
github.com/microsoft/kiota/abstractions/go.RegisterDefaultSerializer(0x100c0001100b0)
/Users/theber/go/pkg/mod/github.com/microsoft/kiota/abstractions/[email protected]/api_client_builder.go:12 +0x5e fp=0xc000979c50 sp=0xc000979c10 pc=0x14a64be
github.com/microsoftgraph/msgraph-sdk-go.NewGraphServiceClient({0x1ee2f90, 0xc0004fe410})
/Users/theber/go/pkg/mod/github.com/microsoftgraph/[email protected]/graph_service_client.go:271 +0xc5 fp=0xc000979c88 sp=0xc000979c50 pc=0x1663385

Crash is occurring in line 12 s.DefaultSerializationWriterFactoryInstance.ContentTypeAssociatedFactories[contentType] = factory

package abstractions

import (
        s "github.com/microsoft/kiota/abstractions/go/serialization"
)

// RegisterDefaultSerializer registers the default serializer to the registry singleton to be used by the request adapter.
func RegisterDefaultSerializer(metaFactory func() s.SerializationWriterFactory) {
        factory := metaFactory()
        contentType, err := factory.GetValidContentType()
        if err == nil && contentType != "" {
                s.DefaultSerializationWriterFactoryInstance.ContentTypeAssociatedFactories[contentType] = factory
        }
}

// RegisterDefaultDeserializer registers the default deserializer to the registry singleton to be used by the request adapter.
func RegisterDefaultDeserializer(metaFactory func() s.ParseNodeFactory) {
        factory := metaFactory()
        contentType, err := factory.GetValidContentType()
        if err == nil && contentType != "" {
                s.DefaultParseNodeFactoryInstance.ContentTypeAssociatedFactories[contentType] = factory
        }
}

Cannot use "create user" example - missing functions

Context

Hi I'm trying to run the "create user" example from the ms graph docs

The code is

graphClient := msgraphsdk.NewGraphServiceClient(requestAdapter)

requestBody := msgraphsdk.NewUser()
accountEnabled := true
requestBody.SetAccountEnabled(&accountEnabled)
displayName := "Adele Vance"
requestBody.SetDisplayName(&displayName)
mailNickname := "AdeleV"
requestBody.SetMailNickname(&mailNickname)
userPrincipalName := "[email protected]"
requestBody.SetUserPrincipalName(&userPrincipalName)
passwordProfile := msgraphsdk.NewPasswordProfile()
requestBody.SetPasswordProfile(passwordProfile)
forceChangePasswordNextSignIn := true
passwordProfile.SetForceChangePasswordNextSignIn(&forceChangePasswordNextSignIn)
password := "xWwvJ]6NMw+bWH-d"
passwordProfile.SetPassword(&password)
options := &msgraphsdk.UsersRequestBuilderPostOptions{
	Body: requestBody,
}
result, err := graphClient.Users().Post(options)

the msgraphsdk import looks like

import msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"

currently I'm using version v0.16.0

My problem

I can't get the example running. The functions NewUser, NewPasswordProfile & UserRequestBuilderPostOptions are undefined.

Is there maybe some import I'm missing or are these function maybe not a part of msgraphsdk but part of another package?
Would be nice to get some help on this, especially since it feels like the fix will be trivial.

Example in README does not work

Changing scope from []string{"Mail.Read", "Mail.Send"} to []string{"User.Read"}, the example returned the following error when executing client.Me().Get(nil).

To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXXXXX to authenticate.
2021/11/21 00:01:43 Error getting user: (invalid_client) AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret'.
Trace ID: b2f2fc4f-9734-4001-91a3-2165e3ac1100
Correlation ID: 64c27318-e30e-4d62-9a33-949b045b9bf8
Timestamp: 2021-11-20 15:01:43Z

Here is what permissions I have granted to the app.

image

Here is my environment

go 1.17

require (
	github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.12.0
	github.com/microsoft/kiota/authentication/go/azure v0.0.0-20211119142553-1ee6842528d6
	github.com/microsoftgraph/msgraph-sdk-go v0.2.0
)

Question about NextLink

Hi!
I'm trying to use Go Graph SDK and I'm stuck! I am able to request AD users but I get only first 100 users with NextLink property which contains link to additional data.
How should I use this link to fetch next 100 users with Go SDK?
Example of my code:

	...
	client := msgraphsdk.NewGraphServiceClient(adapter)
	result, err := client.Users().Get(&opts)
	if err != nil {
		log.Fatal(err)
	}
	var users []graph.User
	users = append(users, result.GetValue()...)
	fmt.Println(*result.GetNextLink())

Issue with go get -u github.com/microsoftgraph/msgraph-sdk-go

I'm brand new to go an and might be completely my own fault but getting this error when running
go get -u github.com/microsoftgraph/msgraph-sdk-go
with this error

# github.com/microsoftgraph/msgraph-sdk-go-core
../pkg/mod/github.com/microsoftgraph/[email protected]/page_iterator.go:147:47: cannot use *requestInfo (type abstractions.RequestInformation) as type *abstractions.RequestInformation in argument to pI.reqAdapter.NetHttpRequestAdapter.SendAsync

Only getting this error on PopOS and not Mac

Failed to create an application with the graph service client

I'm trying to create an app and I see it gets created, but it fails at the deserialization. Here is the sample function:

func GraphClient(tenantID, clientID, clientSecret string) (*graph.Application, error) {
    cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, clientSecret, nil)
    if err != nil {
        return nil, errors.Wrap(err, "failed to create credential")
    }
    auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{"https://graph.microsoft.com/.default"})
    if err != nil {
        return nil, errors.Wrap(err, "failed to create authentication provider")
    }
    adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
    if err != nil {
        return nil, errors.Wrap(err, "failed to create request adapter")
    }
    client := msgraphsdk.NewGraphServiceClient(adapter)
    name := "kiota"
    appOptions := &applications.ApplicationsRequestBuilderPostOptions{
        Body: graph.NewApplication(),
    }
    appOptions.Body.SetDisplayName(&name)
    return client.Applications().Post(appOptions)
}

This is the error i'm getting:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x6658e7]
goroutine 1 [running]:
github.com/microsoft/kiota/serialization/go/json.(*JsonParseNode).GetObjectValue(0xc000013460, 0xc000024230)
        /home/anramase/go/pkg/mod/github.com/microsoft/kiota/serialization/go/[email protected]/json_parse_node.go:161 +0x1a7
github.com/microsoft/kiota/http/go/nethttp.(*NetHttpRequestAdapter).SendAsync(0xc0000c4230, {0x1, 0x0, 0xc000095320, 0xc000095350, {0xc0000bc180, 0x17, 0x18}, 0xc000095290, {0x70b28c, ...}, ...}, ...)
        /home/anramase/go/pkg/mod/github.com/microsoft/kiota/http/go/[email protected]/nethttp_request_adapter.go:170 +0x158
github.com/microsoftgraph/msgraph-sdk-go/applications.(*ApplicationsRequestBuilder).Post(0xc0000952f0, 0x768ee8)
        /home/anramase/go/pkg/mod/github.com/microsoftgraph/[email protected]/applications/applications_request_builder.go:166 +0xc2
github.com/aramase/graphsdk/pkg/cloud.GraphClient({0x703c65, 0x300000002}, {0x703ab5, 0xc00003c738}, {0x702bde, 0xc0000001a0})
        /home/anramase/go/src/github.com/aramase/graphsdk/pkg/cloud/graphsdk.go:33 +0x208
main.main()
        /home/anramase/go/src/github.com/aramase/graphsdk/cmd/main.go:21 +0x55

Versions of the sdk being used from go.mod:

	github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.12.0
	github.com/microsoft/kiota/authentication/go/azure v0.0.0-20211108143922-c77efb191939
	github.com/microsoftgraph/msgraph-sdk-go v0.0.3

cc @baywet

Directory deleted items - SDK generates code incorrectly.

As described here:
https://docs.microsoft.com/en-us/graph/api/directory-deleteditems-list?view=graph-rest-1.0&tabs=http

The OData cast type is a required part of the URI and calling GET /directory/deleteditems without a type is not supported.

The SDK expects GET /directory/deleteditems which is incorrect.

Should be something like this:
client.Directory().DeletedItems().Users().Get()

Tried client.Directory().DeletedItemsById("...") but this returns the wrong type (A single object).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.