Coder Social home page Coder Social logo

hamilton's Introduction

Hamilton is a Go SDK for Microsoft Graph

This is a working Go client for the Microsoft Graph API. It is actively maintained and has growing support for services and objects in Azure Active Directory.

Documentation

See pkg.go.dev.

Features

  • Automatic retries for failed requests and handling of eventual consistency on writes due to propagation delays
  • Automatic paging of results
  • Native model structs for marshaling and unmarshaling
  • Support for national clouds including US Government (L4 and L5) and China
  • Support for both the v1.0 and beta API endpoints
  • Ability to inject middleware functions for logging etc
  • OData parsing in API responses and support for OData queries such as filters, sorting, searching, expand and select
  • Built-in authentication support using methods including client credentials (both client secret and client certificate), obtaining access tokens via Azure CLI, managed identity via the Azure Metadata Service, and federated credentials with a built-in authorizer for GitHub OIDC.
  • Compatibility with go-autorest, both for consuming autorest authorizers, and for providing autorest-compatible authorizers (see the hamilton-autorest add-on module)

Getting Started

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/manicminer/hamilton/auth"
	"github.com/manicminer/hamilton/environments"
	"github.com/manicminer/hamilton/msgraph"
	"github.com/manicminer/hamilton/odata"
)

var (
	tenantId     = os.Getenv("TENANT_ID")
	clientId     = os.Getenv("CLIENT_ID")
	clientSecret = os.Getenv("CLIENT_SECRET")
)

func main() {
	ctx := context.Background()

	environment := environments.Global

	authConfig := &auth.Config{
		Environment:            environment,
		TenantID:               tenantId,
		ClientID:               clientId,
		ClientSecret:           clientSecret,
		EnableClientSecretAuth: true,
	}

	authorizer, err := authConfig.NewAuthorizer(ctx, environment.MsGraph)
	if err != nil {
		log.Fatal(err)
	}

	client := msgraph.NewUsersClient(tenantId)
	client.BaseClient.Authorizer = authorizer

	users, _, err := client.List(ctx, odata.Query{})
	if err != nil {
		log.Println(err)
		return
	}
	if users == nil {
		log.Println("bad API response, nil result received")
		return
	}
	for _, user := range *users {
		fmt.Printf("%s: %s <%s>\n", *user.ID(), *user.DisplayName, *user.UserPrincipalName)
	}
}

Configure retry limit for all failed requests

client := msgraph.NewUsersClient(tenantId)
client.BaseClient.Authorizer = authorizer
client.BaseClient.RetryableClient.RetryMax = 8

Disable eventual consistency handling

Note: this does not disable auto-retries for failed requests (e.g. HTTP 429 or 500 responses)

client := msgraph.NewUsersClient(tenantId)
client.BaseClient.Authorizer = authorizer
client.BaseClient.DisableRetries = true

Log requests and responses

requestLogger := func(req *http.Request) (*http.Request, error) {
	if req != nil {
		if dump, err := httputil.DumpRequestOut(req, true); err == nil {
			log.Printf("%s\n", dump)
		}
	}
	return req, nil
}

responseLogger := func(req *http.Request, resp *http.Response) (*http.Response, error) {
	if resp != nil {
		if dump, err := httputil.DumpResponse(resp, true); err == nil {
			log.Printf("%s\n", dump)
		}
	}
	return resp, nil
}

client := msgraph.NewUsersClient(tenantId)
client.BaseClient.Authorizer = authorizer
client.BaseClient.DisableRetries = true
client.BaseClient.RequestMiddlewares = &[]msgraph.RequestMiddleware{requestLogger}
client.BaseClient.ResponseMiddlewares = &[]msgraph.ResponseMiddleware{responseLogger}

Contributing

Contributions are welcomed! Please note that clients must have tests that cover all methods where feasible.

Please raise a pull request on GitHub to submit contributions. Bug reports and feature requests are happily received.

Testing

Testing requires an Azure AD tenant and real credentials. Note that some tests require an Azure AD Premium P2 license and/or an Office 365 license. You can authenticate with any supported method for the client tests, and the auth tests are split by authentication method.

ℹī¸ You can sign up for the Microsoft 365 Developer Program which offers a Microsoft 365 E5 subscription for 25 users, at no cost for development purposes.

Note that each client generally has a single test that exercises all methods. This is to help ensure that test objects are cleaned up where possible. Where tests fail, often objects will be left behind and should be cleaned up separately. The test-cleanup command can be used to delete leftover test objects in the event of test failure.

It's recommended to use an isolated tenant for testing and not a production tenant.

To run all the tests:

$ make test

hamilton's People

Contributors

manicminer avatar markdordoy avatar tsologub avatar liammoat avatar michaljirman avatar swissgipfel avatar simongottschlag avatar askew avatar alexwilcox9 avatar joostvdoorn avatar jarifibrahim avatar tomasmota avatar kaovd avatar computeracer avatar ekristen avatar panic-kbutton avatar t3mi avatar pier62350 avatar rohrerb avatar amarbut24 avatar yriveiro avatar webframp avatar moriyoshi avatar maxsokolovsky avatar mblaschke avatar kennethmldk avatar dhohengassner avatar rikkuness avatar

Watchers

 avatar

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.