msgraphgocore

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2024 License: MIT Imports: 18 Imported by: 29

README

Microsoft Graph Core SDK for Go

PkgGoDev Coverage Sonarcloud Status

Get started with the Microsoft Graph Core SDK for Go by integrating the Microsoft Graph API into your Go application! You can also have a look at the Go documentation

Note: Although you can use this library directly, we recommend you use the v1 or beta library which rely on this library and additionally provide a fluent style Go API and models.

Note: The Microsoft Graph Go SDK is currently in Release Candidate (RC) version starting from version 0.34.1. The SDK is still undergoing testing but minimum breaking changes should be expected. Checkout the known limitations.

Samples and usage guide

1. Installation

go get github.com/microsoftgraph/msgraph-sdk-go-core
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity

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 GraphRequestAdapterBase 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.

import (
    azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    a          "github.com/microsoftgraph/msgraph-sdk-go-core/authentication"
    "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)
}

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

2.3 Get a Request Adapter object

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

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

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

3. Make requests against the service

After you have a GraphRequestAdapterBase 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 details

To retrieve the user's details

import abs "github.com/microsoft/kiota-abstractions-go"

requestInf := abs.NewRequestInformation()
targetUrl, err := url.Parse("https://graph.microsoft.com/v1.0/me")
if err != nil {
    fmt.Printf("Error parsing URL: %v\n", err)
}
requestInf.SetUri(*targetUrl)

// User is your own type that implements Parsable or comes from the service library
user, err := adapter.SendAsync(*requestInf, func() { return &User }, nil)

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

4. Issues

For known issues, see issues.

5. Contributions

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

6. License

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

7. Third-party notices

Third-party notices

Documentation

Index

Constants

View Source
const BatchRequestErrorRegistryKey = "BATCH_REQUEST_ERROR_REGISTRY_KEY"
View Source
const MaxBatchRequests = 4

Variables

View Source
var CoreVersion = "1.1.0"
View Source
var ReplacementPairs = map[string]string{"/users/me-token-to-replace": "/me"}

Functions

func CreateBatchRequestItemDiscriminator added in v0.30.0

func CreateBatchRequestItemDiscriminator(serialization.ParseNode) (serialization.Parsable, error)

CreateBatchRequestItemDiscriminator creates a new instance of the appropriate class based on discriminator value

func CreateBatchResponseDiscriminator added in v0.30.0

func CreateBatchResponseDiscriminator(serialization.ParseNode) (serialization.Parsable, error)

CreateBatchResponseDiscriminator creates a new instance of the appropriate class based on discriminator value

func DeRegisterError added in v0.30.0

func DeRegisterError(key string) error

func GetBatchResponseById added in v0.30.0

func GetBatchResponseById[T serialization.Parsable](resp BatchResponse, itemId string, constructor absser.ParsableFactory) (T, error)

GetBatchResponseById returns the response of the batch request item with the given id.

func GetDefaultClient

func GetDefaultClient(options *GraphClientOptions, middleware ...khttp.Middleware) *nethttp.Client

GetDefaultClient creates a new http client with a preconfigured middleware pipeline

func GetDefaultMiddlewaresWithOptions

func GetDefaultMiddlewaresWithOptions(options *GraphClientOptions) []khttp.Middleware

GetDefaultMiddlewaresWithOptions creates a default slice of middleware for the Graph Client.

func GetErrorFactoryFromRegistry added in v0.30.0

func GetErrorFactoryFromRegistry(key string) (abstractions.ErrorMappings, bool)

func RegisterError added in v0.30.0

func RegisterError(key string, value abstractions.ErrorMappings) error

Types

type BatchItem added in v0.30.0

type BatchItem interface {
	serialization.Parsable
	GetId() *string
	SetId(value *string)
	GetMethod() *string
	SetMethod(value *string)
	GetUrl() *string
	SetUrl(value *string)
	GetHeaders() RequestHeader
	SetHeaders(value RequestHeader)
	GetBody() RequestBody
	SetBody(value RequestBody)
	GetDependsOn() []string
	SetDependsOn(value []string)
	GetStatus() *int32
	SetStatus(value *int32)
	DependsOnItem(item BatchItem)
}

BatchItem is an instance of the BatchRequest payload to be later serialized to a json payload

func NewBatchItem added in v0.30.0

func NewBatchItem() BatchItem

NewBatchItem creates an instance of BatchItem

type BatchRequest added in v0.30.0

type BatchRequest interface {
	serialization.Parsable
	GetRequests() []BatchItem
	SetRequests(requests []BatchItem)
	AddBatchRequestStep(reqInfo abstractions.RequestInformation) (BatchItem, error)
	Send(ctx context.Context, adapter abstractions.RequestAdapter) (BatchResponse, error)
}

BatchRequest models all the properties of a batch request

func NewBatchRequest added in v0.30.0

func NewBatchRequest(adapter abstractions.RequestAdapter) BatchRequest

NewBatchRequest creates an instance of BatchRequest

type BatchRequestCollection added in v0.36.0

type BatchRequestCollection struct {
	// contains filtered or unexported fields
}

func NewBatchRequestCollection added in v0.36.0

func NewBatchRequestCollection(adapter abstractions.RequestAdapter) *BatchRequestCollection

NewBatchRequestCollection creates an instance of a BatchRequestCollection with a default request limit

func NewBatchRequestCollectionWithLimit added in v0.36.0

func NewBatchRequestCollectionWithLimit(adapter abstractions.RequestAdapter, batchLimit int) *BatchRequestCollection

NewBatchRequestCollectionWithLimit creates an instance of a BatchRequestCollection with a defined limit in requests

func (*BatchRequestCollection) AddBatchRequestStep added in v0.36.0

func (b *BatchRequestCollection) AddBatchRequestStep(reqInfo abstractions.RequestInformation) (BatchItem, error)

AddBatchRequestStep converts RequestInformation to a BatchItem and adds it to a BatchRequestCollection

func (*BatchRequestCollection) Send added in v0.36.0

Send serializes and sends the batch request to the server

type BatchResponse added in v0.30.0

type BatchResponse interface {
	serialization.Parsable
	GetResponses() []BatchItem
	SetResponses(responses []BatchItem)
	AddResponses(responses []BatchItem)
	GetResponseById(itemId string) BatchItem
	GetFailedResponses() map[string]int32
	GetStatusCodes() map[string]int32
}

BatchResponse instance of batch request result payload

func NewBatchResponse added in v0.36.0

func NewBatchResponse() BatchResponse

type GraphClientOptions

type GraphClientOptions struct {
	GraphServiceVersion        string
	GraphServiceLibraryVersion string
}

GraphClientOptions represents a combination of GraphServiceVersion and GraphServiceLibraryVersion

GraphServiceVersion is version of the targeted service. GraphServiceLibraryVersion is the version of the service library

type GraphRequestAdapterBase

type GraphRequestAdapterBase struct {
	khttp.NetHttpRequestAdapter
}

GraphRequestAdapterBase is the core service used by GraphServiceClient to make requests to Microsoft Graph.

func NewGraphRequestAdapterBase

func NewGraphRequestAdapterBase(authenticationProvider absauth.AuthenticationProvider, clientOptions GraphClientOptions) (*GraphRequestAdapterBase, error)

NewGraphRequestAdapterBase creates a new GraphRequestAdapterBase with the given parameters

func NewGraphRequestAdapterBaseWithParseNodeFactory

func NewGraphRequestAdapterBaseWithParseNodeFactory(authenticationProvider absauth.AuthenticationProvider, clientOptions GraphClientOptions, parseNodeFactory absser.ParseNodeFactory) (*GraphRequestAdapterBase, error)

NewGraphRequestAdapterBaseWithParseNodeFactory creates a new GraphRequestAdapterBase with the given parameters

func NewGraphRequestAdapterBaseWithParseNodeFactoryAndSerializationWriterFactory

func NewGraphRequestAdapterBaseWithParseNodeFactoryAndSerializationWriterFactory(authenticationProvider absauth.AuthenticationProvider, clientOptions GraphClientOptions, parseNodeFactory absser.ParseNodeFactory, serializationWriterFactory absser.SerializationWriterFactory) (*GraphRequestAdapterBase, error)

NewGraphRequestAdapterBaseWithParseNodeFactoryAndSerializationWriterFactory creates a new GraphRequestAdapterBase with the given parameters

func NewGraphRequestAdapterBaseWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient

func NewGraphRequestAdapterBaseWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient(authenticationProvider absauth.AuthenticationProvider, clientOptions GraphClientOptions, parseNodeFactory absser.ParseNodeFactory, serializationWriterFactory absser.SerializationWriterFactory, httpClient *nethttp.Client) (*GraphRequestAdapterBase, error)

NewGraphRequestAdapterBaseWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient creates a new GraphRequestAdapterBase with the given parameters

type GraphTelemetryHandler

type GraphTelemetryHandler struct {
	// contains filtered or unexported fields
}

GraphTelemetryHandler is a middleware handler that adds telemetry headers to requests.

func NewGraphTelemetryHandler

func NewGraphTelemetryHandler(options *GraphClientOptions) *GraphTelemetryHandler

NewGraphTelemetryHandler creates a new GraphTelemetryHandler.

func (GraphTelemetryHandler) Intercept

func (middleware GraphTelemetryHandler) Intercept(pipeline khttp.Pipeline, middlewareIndex int, req *nethttp.Request) (*nethttp.Response, error)

type PageIterator added in v0.0.6

type PageIterator[T interface{}] struct {
	// contains filtered or unexported fields
}

PageIterator represents an iterator object that can be used to get subsequent pages of a collection.

func NewPageIterator added in v0.0.6

func NewPageIterator[T interface{}](res interface{}, reqAdapter abstractions.RequestAdapter, constructorFunc serialization.ParsableFactory) (*PageIterator[T], error)

NewPageIterator creates an iterator instance

It has three parameters. res is the graph response from the initial request and represents the first page. reqAdapter is used for getting the next page and constructorFunc is used for serializing next page's response to the specified type.

func (pI *PageIterator[T]) GetOdataDeltaLink() *string

GetOdataDeltaLink returns the @odata.deltaLink value in current paged result.

func (pI *PageIterator[T]) GetOdataNextLink() *string

GetOdataNextLink returns the @odata.nextLink value in the current page result.

func (*PageIterator[T]) Iterate added in v0.0.6

func (pI *PageIterator[T]) Iterate(context context.Context, callback func(pageItem T) bool) error

Iterate traverses all pages and enumerates all items in the current page and returns an error if something goes wrong.

Iterate receives a callback function which is called with each item in the current page as an argument. The callback function returns a boolean. To traverse and enumerate all pages always return true and to pause traversal and enumeration return false from the callback.

Example

pageIterator, err := NewPageIterator(resp, reqAdapter, parsableFactory)
callbackFunc := func (pageItem interface{}) bool {
    fmt.Println(page item.GetDisplayName())
    return true
}
err := pageIterator.Iterate(context.Background(), callbackFunc)

func (*PageIterator[T]) SetHeaders added in v0.0.6

func (pI *PageIterator[T]) SetHeaders(headers *abstractions.RequestHeaders)

SetHeaders provides headers for requests made to get subsequent pages

Headers in the initial request -- request to get the first page -- are not included in subsequent page requests.

func (*PageIterator[T]) SetReqOptions added in v0.0.6

func (pI *PageIterator[T]) SetReqOptions(reqOptions []abstractions.RequestOption)

SetReqOptions provides configuration for handlers during requests for subsequent pages

type PageResult added in v0.0.6

type PageResult[T interface{}] struct {
	// contains filtered or unexported fields
}

PageResult represents a page object built from a graph response object

type PageWithOdataDeltaLink interface {
	GetOdataDeltaLink() *string
}

PageWithOdataDeltaLink represents a contract with the GetOdataDeltaLink() method

type PageWithOdataNextLink interface {
	GetOdataNextLink() *string
}

PageWithOdataNextLink represents a contract with the GetOdataNextLink() method

type RequestBody added in v0.30.0

type RequestBody map[string]interface{}

RequestBody is a type alias for http request bodies

func (RequestBody) GetFieldDeserializers added in v0.30.0

func (br RequestBody) GetFieldDeserializers() map[string]func(serialization.ParseNode) error

GetFieldDeserializers the deserialization information for the current model

func (RequestBody) Serialize added in v0.30.0

func (br RequestBody) Serialize(writer serialization.SerializationWriter) error

Serialize serializes information the current object

type RequestHeader added in v0.30.0

type RequestHeader map[string]string

RequestHeader is a type alias for http request headers

func (RequestHeader) GetFieldDeserializers added in v0.30.0

func (br RequestHeader) GetFieldDeserializers() map[string]func(serialization.ParseNode) error

GetFieldDeserializers the deserialization information for the current model

func (RequestHeader) Serialize added in v0.30.0

Serialize serializes information the current object

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL