Docs

You are viewing an archived version of the docs.Go to latest version

Use Clerk Go for Backend API Operations

The following example demonstrates how to use the Clerk Go SDK to execute Clerk Backend API operations.

By executing the code in the snippet below, you will:

  • Create an organization and update its slug.
  • Fetch all organization memberships and loop through them to get the first one.
  • Get more details about the organization's user.

Note

Your Clerk secret key is required. If you are signed into your Clerk Dashboard, your secret key should become visible by selecting the eye icon. Otherwise, you can retrieve your Clerk secret key from the Clerk Dashboard on the API Keys page.

main.go
import (
    "github.com/clerk/clerk-sdk-go/v2"
    "github.com/clerk/clerk-sdk-go/v2/organization"
    "github.com/clerk/clerk-sdk-go/v2/organizationmembership"
    "github.com/clerk/clerk-sdk-go/v2/user"
)

func main() {
  // Each API operation requires a context.Context as the first argument.
  ctx := context.Background()

  // Set the API key
  clerk.SetKey("YOUR_SECRET_KEY")

  // Create an organization
  org, err := organization.Create(ctx, &organization.CreateParams{
      Name: clerk.String("Clerk Inc"),
  })
  if err != nil {
    // You can get additional information on the error, if it can
    // be type-cast to clerk.APIErrorResponse.
    if apiErr, ok := err.(*clerk.APIErrorResponse); ok {
      apiErr.TraceID
      apiErr.Error()
      apiErr.Response.RawJSON
    }
    // handle the error
    panic(err)
  }

  // Update the organization
  org, err = organization.Update(ctx, org.ID, &organization.UpdateParams{
      Slug: clerk.String("clerk"),
  })
  if err != nil {
    // handle the error
    panic(err)
  }

  // List organization memberships
  listParams := organizationmembership.ListParams{}
  listParams.Limit = clerk.Int64(10)
  memberships, err := organizationmembership.List(ctx, params)
  if err != nil {
    // handle the error
    panic(err)
  }
  if memberships.TotalCount < 0 {
      return
  }
  membership := memberships[0]

  // Get a user
  usr, err := user.Get(ctx, membership.UserID)
  if err != nil {
    // handle the error
    panic(err)
  }
}

Feedback

What did you think of this content?

Last updated on