Skip to content

Instantly share code, notes, and snippets.

@kfcampbell
Last active December 8, 2023 23:25
Show Gist options
  • Save kfcampbell/0214851ce0ee9844f957cdbfb06910d4 to your computer and use it in GitHub Desktop.
Save kfcampbell/0214851ce0ee9844f957cdbfb06910d4 to your computer and use it in GitHub Desktop.
Use the generated Go SDK

Using the generated Go SDK

  • Install Go 1.21
  • Export a valid GITHUB_TOKEN
  • Create a directory for your project
  • From your directory, run go mod init github.com/yourUsername/yourProjectName
  • Create a main.go file with the following contents in it:
package main

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

	abstractions "github.com/microsoft/kiota-abstractions-go"
	http "github.com/microsoft/kiota-http-go"
	auth "github.com/octokit/go-sdk/github/authentication"
	"github.com/octokit/go-sdk/github/octokit"
	"github.com/octokit/go-sdk/github/octokit/octocat"
	"github.com/octokit/go-sdk/github/octokit/user"
)

func main() {
	token := os.Getenv("GITHUB_TOKEN")
	if token == "" {
		log.Fatalf("GITHUB_TOKEN must be provided")
	}

	tokenProvider := auth.NewTokenProvider(
		auth.WithAuthorizationToken(token))
	/* other options: WithUserAgent, WithAPIVersion, or a user-defined function.
	   if not present, sensible defaults will be used */

	adapter, err := http.NewNetHttpRequestAdapter(tokenProvider)
	if err != nil {
		log.Fatalf("Error creating request adapter: %v", err)
	}

	client := octokit.NewApiClient(adapter)

	// unauthenticated request
	s := "Salutations"

	// create headers that accept json back; our spec says octet-stream
	// but that's not actually what the API returns in this case
	headers := abstractions.NewRequestHeaders()
	_ = headers.TryAdd("Accept", "application/vnd.github.v3+json")

	octocatRequestConfig := &octocat.OctocatRequestBuilderGetRequestConfiguration{
		QueryParameters: &octocat.OctocatRequestBuilderGetQueryParameters{
			S: &s,
		},
		Headers: headers,
	}
	cat, err := client.Octocat().Get(context.Background(), octocatRequestConfig)
	if err != nil {
		log.Fatalf("error getting octocat: %v", err)
	}
	fmt.Printf("%v\n", string(cat))

	// authenticated request for private user emails
	emailsRequestConfig := &user.EmailsRequestBuilderGetRequestConfiguration{}
	userEmails, err := client.User().Emails().Get(context.Background(), emailsRequestConfig)
	if err != nil {
		log.Fatalf("%v\n", err)
	}

	for _, v := range userEmails {
		fmt.Printf("%v\n", *v.GetEmail())
	}
}
  • Run go mod tidy
  • Run go run main.go to see the successful requests!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment