Documentation
¶
Overview ¶
Package msgraph provides a small Microsoft Graph REST client.
Index ¶
- Constants
- Variables
- func BodyContentTypePreference(contentType string) string
- func IsForbidden(err error) bool
- func IsNotFound(err error) bool
- func IsStatus(err error, statusCode int) bool
- func IsThrottled(err error) bool
- func IsUnauthorized(err error) bool
- func Items[T any](ctx context.Context, client *Client, path string, params Params, ...) iter.Seq2[T, error]
- func MergeScopes(values ...[]string) []string
- func Pages[T any](ctx context.Context, client *Client, path string, params Params, ...) iter.Seq2[Page[T], error]
- type APIError
- type BatchError
- type BatchRequest
- type BatchResponse
- type Client
- func (c *Client) Batch(ctx context.Context, requests []BatchRequest) ([]BatchResponse, error)
- func (c *Client) BatchStrict(ctx context.Context, requests []BatchRequest) ([]BatchResponse, error)
- func (c *Client) Delete(ctx context.Context, path string, params Params, out any) (*Response, error)
- func (c *Client) Do(ctx context.Context, req Request, out any) (*Response, error)
- func (c *Client) Get(ctx context.Context, path string, params Params, out any) (*Response, error)
- func (c *Client) Patch(ctx context.Context, path string, params Params, body, out any) (*Response, error)
- func (c *Client) Post(ctx context.Context, path string, params Params, body, out any) (*Response, error)
- func (c *Client) TranslateExchangeIDs(ctx context.Context, user string, inputIDs []string, ...) ([]TranslatedExchangeID, *Response, error)
- type ExchangeIDFormat
- type Option
- type Page
- type PageOption
- type Params
- type Permission
- type PermissionSuggestion
- type Request
- type Response
- type TokenSource
- type TokenSourceFunc
- type TranslateExchangeIDsRequest
- type TranslateExchangeIDsResponse
- type TranslatedExchangeID
Constants ¶
const ( // PreferIDTypeImmutableID asks Graph to return IDs that survive moves. PreferIDTypeImmutableID = `IdType="ImmutableId"` // PreferBodyContentTypeText asks Outlook mail endpoints to return text bodies. PreferBodyContentTypeText = `outlook.body-content-type="text"` // PreferBodyContentTypeHTML asks Outlook mail endpoints to return HTML bodies. PreferBodyContentTypeHTML = `outlook.body-content-type="html"` // ConsistencyLevelEventual enables Graph advanced query capabilities where // endpoints require the ConsistencyLevel header. ConsistencyLevelEventual = "eventual" )
const ( // GraphResourceAppID is the Microsoft Graph service principal app ID. GraphResourceAppID = "00000003-0000-0000-c000-000000000000" // GraphCLIClientID is Microsoft's first-party Microsoft Graph Command Line // Tools public client app ID. GraphCLIClientID = "14d82eec-204b-4c2f-b7e8-296a70dab67e" MailReadDelegatedID = "570282fd-fa5c-430d-a7fd-fc8dc98a9dca" MailReadWriteDelegatedID = "024d486e-b451-40bb-833d-3e66d98c5c73" MailSendDelegatedID = "e383f46e-2787-4529-855e-0e479a3ffac0" UserReadDelegatedID = "e1fe6dd8-ba31-4d61-89e7-88639da4683d" )
const ( ScopeUserRead = "User.Read" ScopeUserReadBasicAll = "User.ReadBasic.All" ScopeUserReadWriteAll = "User.ReadWrite.All" ScopeMailRead = "Mail.Read" ScopeMailReadWrite = "Mail.ReadWrite" ScopeMailSend = "Mail.Send" ScopeCalendarsRead = "Calendars.Read" ScopeCalendarsReadWrite = "Calendars.ReadWrite" ScopeContactsRead = "Contacts.Read" ScopeContactsReadWrite = "Contacts.ReadWrite" ScopeFilesRead = "Files.Read" ScopeFilesReadWrite = "Files.ReadWrite" ScopeGroupReadAll = "Group.Read.All" ScopeGroupReadWriteAll = "Group.ReadWrite.All" ScopeDirectoryReadAll = "Directory.Read.All" )
Variables ¶
var ( ErrPageCycle = errors.New("msgraph: repeated nextLink") ErrMaxPagesExceeded = errors.New("msgraph: max pages exceeded") )
Pagination errors returned by Pages and Items.
var CommonPermissions = []Permission{ { Name: ScopeMailRead, ID: MailReadDelegatedID, Kind: "delegated", PersonalAccountsAllowed: true, }, { Name: ScopeMailReadWrite, ID: MailReadWriteDelegatedID, Kind: "delegated", PersonalAccountsAllowed: true, }, { Name: ScopeMailSend, ID: MailSendDelegatedID, Kind: "delegated", PersonalAccountsAllowed: true, }, { Name: ScopeUserRead, ID: UserReadDelegatedID, Kind: "delegated", PersonalAccountsAllowed: true, }, {Name: ScopeUserReadBasicAll, Kind: "delegated"}, {Name: ScopeUserReadWriteAll, Kind: "delegated", AdminConsentRequired: true}, {Name: ScopeCalendarsRead, Kind: "delegated", PersonalAccountsAllowed: true}, {Name: ScopeCalendarsReadWrite, Kind: "delegated", PersonalAccountsAllowed: true}, {Name: ScopeContactsRead, Kind: "delegated", PersonalAccountsAllowed: true}, {Name: ScopeContactsReadWrite, Kind: "delegated", PersonalAccountsAllowed: true}, {Name: ScopeFilesRead, Kind: "delegated", PersonalAccountsAllowed: true}, {Name: ScopeFilesReadWrite, Kind: "delegated", PersonalAccountsAllowed: true}, {Name: ScopeGroupReadAll, Kind: "delegated", AdminConsentRequired: true}, {Name: ScopeGroupReadWriteAll, Kind: "delegated", AdminConsentRequired: true}, {Name: ScopeDirectoryReadAll, Kind: "delegated", AdminConsentRequired: true}, }
CommonPermissions is a hand-curated seed set. The full catalog should be generated from the Graph service principal in a later package.
var ErrRequestFailed = errors.New("msgraph: request failed")
ErrRequestFailed is wrapped by APIError for non-2xx Graph responses.
Functions ¶
func BodyContentTypePreference ¶
BodyContentTypePreference returns an Outlook body-content Prefer directive.
func IsForbidden ¶
IsForbidden reports whether err is a Graph 403 response.
func IsNotFound ¶
IsNotFound reports whether err is a Graph 404 response.
func IsThrottled ¶
IsThrottled reports whether err is a Graph throttling response.
func IsUnauthorized ¶
IsUnauthorized reports whether err is a Graph 401 response.
func Items ¶
func Items[T any](ctx context.Context, client *Client, path string, params Params, opts ...PageOption) iter.Seq2[T, error]
Items returns an iterator over every item in a Graph collection.
func MergeScopes ¶ added in v0.2.0
MergeScopes merges scope slices, preserving first-seen spelling and order.
Types ¶
type BatchError ¶
type BatchError struct {
Responses []BatchResponse
}
BatchError reports one or more failed subresponses from a strict batch call.
func (*BatchError) Error ¶
func (e *BatchError) Error() string
type BatchRequest ¶
type BatchRequest struct {
ID string `json:"id"`
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
Body any `json:"body,omitempty"`
}
BatchRequest is one request inside a Microsoft Graph JSON batch.
type BatchResponse ¶
type BatchResponse struct {
ID string `json:"id"`
Status int `json:"status"`
Headers map[string]string `json:"headers,omitempty"`
Body json.RawMessage `json:"body,omitempty"`
}
BatchResponse is one response inside a Microsoft Graph JSON batch.
func FailedBatchResponses ¶
func FailedBatchResponses(responses []BatchResponse) []BatchResponse
FailedBatchResponses returns every subresponse with a non-2xx status.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a small Microsoft Graph REST client.
func New ¶
func New(token TokenSource, opts ...Option) (*Client, error)
New creates a Microsoft Graph client.
func (*Client) Batch ¶
func (c *Client) Batch(ctx context.Context, requests []BatchRequest) ([]BatchResponse, error)
Batch sends a Microsoft Graph JSON batch request.
func (*Client) BatchStrict ¶
func (c *Client) BatchStrict(ctx context.Context, requests []BatchRequest) ([]BatchResponse, error)
BatchStrict sends a JSON batch and returns a BatchError when any subrequest status is outside 2xx. The full response slice is still returned so callers can inspect successes and failures together.
func (*Client) Delete ¶
func (c *Client) Delete(ctx context.Context, path string, params Params, out any) (*Response, error)
Delete sends a Graph DELETE request.
func (*Client) Do ¶
Do sends req and decodes a successful JSON response into out. If out is an io.Writer, the response body is streamed into it instead.
func (*Client) Patch ¶
func (c *Client) Patch(ctx context.Context, path string, params Params, body, out any) (*Response, error)
Patch sends a Graph PATCH request.
func (*Client) Post ¶
func (c *Client) Post(ctx context.Context, path string, params Params, body, out any) (*Response, error)
Post sends a Graph POST request.
func (*Client) TranslateExchangeIDs ¶ added in v0.2.0
func (c *Client) TranslateExchangeIDs( ctx context.Context, user string, inputIDs []string, sourceIDType ExchangeIDFormat, targetIDType ExchangeIDFormat, ) ([]TranslatedExchangeID, *Response, error)
TranslateExchangeIDs converts Exchange-family identifiers for the signed-in user ("", "me") or the supplied user ID / UPN.
type ExchangeIDFormat ¶ added in v0.2.0
type ExchangeIDFormat string
ExchangeIDFormat is a Microsoft Graph exchangeIdFormat value.
const ( ExchangeIDFormatEntryID ExchangeIDFormat = "entryId" ExchangeIDFormatEWSID ExchangeIDFormat = "ewsId" ExchangeIDFormatImmutableEntryID ExchangeIDFormat = "immutableEntryId" ExchangeIDFormatRESTID ExchangeIDFormat = "restId" ExchangeIDFormatRESTImmutableEntryID ExchangeIDFormat = "restImmutableEntryId" )
type Option ¶
Option configures a Client.
func WithBaseURL ¶
WithBaseURL sets the Graph base URL. It is mostly useful for tests and sovereign clouds.
func WithHTTPClient ¶
WithHTTPClient sets the HTTP client. A nil client is ignored.
func WithMaxRetries ¶
WithMaxRetries sets the retry count for throttling and transient server errors. Negative values are clamped to zero.
func WithMaxRetryDelay ¶
WithMaxRetryDelay caps retry sleeps, including Retry-After values. A non-positive value disables the cap.
func WithRetryUnsafeMethods ¶
WithRetryUnsafeMethods allows retries for non-idempotent HTTP methods. It is disabled by default because Graph mutations can have side effects before a transient response or connection failure is observed by the client.
func WithSleeper ¶
func WithSleeper(fn sleepFunc) Option
WithSleeper overrides retry sleeping. It exists for tests.
func WithUserAgent ¶
WithUserAgent sets the User-Agent header.
type Page ¶
type Page[T any] struct { Value []T `json:"value"` NextLink string `json:"@odata.nextLink,omitempty"` }
Page is the standard Microsoft Graph collection response shape.
type PageOption ¶
type PageOption func(*pageConfig)
PageOption configures collection iteration.
func WithMaxPages ¶
func WithMaxPages(maxPages int) PageOption
WithMaxPages stops iteration after max pages. A non-positive maxPages leaves page count unlimited, though repeated nextLink values are still rejected.
type Params ¶
type Params struct {
Select []string
Expand []string
OrderBy []string
Search string
Filter string
Top int
Skip int
Custom url.Values
}
Params holds common OData query parameters used by Microsoft Graph.
type Permission ¶
type Permission struct {
Name string
ID string
Kind string
AdminConsentRequired bool
PersonalAccountsAllowed bool
}
Permission describes a known Microsoft Graph permission.
func FindPermission ¶
func FindPermission(nameOrID string) (Permission, bool)
FindPermission returns a known permission by name or ID.
type PermissionSuggestion ¶ added in v0.2.0
type PermissionSuggestion struct {
Method string
Path string
Match string
Scopes []string
Notes []string
}
PermissionSuggestion describes delegated scopes likely needed for a raw Graph request. It is a conservative route-pattern hint, not a substitute for the endpoint-specific Microsoft documentation.
func SuggestDelegatedScopes ¶ added in v0.2.0
func SuggestDelegatedScopes(method, rawPath string) PermissionSuggestion
SuggestDelegatedScopes returns a least-privilege delegated-scope hint for common Microsoft Graph routes. Unknown routes return an empty scope list.
type Request ¶
type Request struct {
Method string
URL string
Params Params
Query url.Values
Header http.Header
Prefer []string
ConsistencyLevel string
Body any
RawBody []byte
ContentType string
}
Request describes a Microsoft Graph request.
type TokenSource ¶
TokenSource returns a Microsoft Graph access token. Implementations should refresh tokens before returning expired credentials.
type TokenSourceFunc ¶
TokenSourceFunc adapts a function into a TokenSource.
type TranslateExchangeIDsRequest ¶ added in v0.2.0
type TranslateExchangeIDsRequest struct {
InputIDs []string `json:"inputIds"`
SourceIDType ExchangeIDFormat `json:"sourceIdType"`
TargetIDType ExchangeIDFormat `json:"targetIdType"`
}
TranslateExchangeIDsRequest is the body accepted by /me/translateExchangeIds and /users/{id}/translateExchangeIds.
type TranslateExchangeIDsResponse ¶ added in v0.2.0
type TranslateExchangeIDsResponse struct {
Value []TranslatedExchangeID `json:"value"`
}
TranslateExchangeIDsResponse is the response from translateExchangeIds.
type TranslatedExchangeID ¶ added in v0.2.0
type TranslatedExchangeID struct {
SourceID string `json:"sourceId"`
TargetID string `json:"targetId"`
}
TranslatedExchangeID is one translated Exchange identifier.