Go API Reference

Go API Reference

Constructor

Magic

The constructor allows you to specify your own API secret key and HTTP request strategy when your application is interacting with the Magic API.

cl := magic.NewClientWithRetry(retries, retryWait, timeout) m := client.New("<api_secret_key>", cl)

Arguments

  • retries (int): Total number of retries to allow.
  • retryWait (time.Duration): A period of time to apply between retry attempts.
  • timeout (time.Duration): A period of time the request is going to wait for a response.
  • api_secret_key (string): Your API secret Key retrieved from the Magic Dashboard.

Returns

  • A Client object that implements methods to interact with Magic API.

Examples

package main import ( "log" "fmt" "time" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/client" ) func main() { cl := magic.NewClientWithRetry(5, time.Second, 10 * time.Second) m := client.New("<api_secret_key>", cl) }

Token Resource

The Token resource provides methods to interact with DID Token.

note

The token resource does not make any API calls to the Magic server.

tk, err := token.NewToken("<DID_TOKEN>") if err != nil { log.Fatalf("Malformed DID token error: %s", err.Error()) } tk.GetIssuer() tk.GetPublicAddress() tk.Validate()

GetIssuer

Extracts the iss from the DID Token.

tk, err := token.NewToken("<DID_TOKEN>") if err != nil { log.Fatalf(err.Error()) } tk.GetIssuer()
Arguments

DID_TOKEN (string): A DID Token generated by a Magic User on the client-side.

Error

token.DIDTokenError if the given DID Token is malformed.

Returns

A Decentralized ID (iss) of the Magic user who generated the DID Token.

Example

We are using Google AppEngine for an example below.

important

It is important to always validate the DID Token before using.

package main import ( "fmt" "log" "net/http" "os" "strings" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/token" ) const authBearer = "Bearer" func main() { http.HandleFunc("/v1/user/info", handler) port := os.Getenv("PORT") log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { if !strings.HasPrefix(r.Header.Get("Authorization"), authBearer) { fmt.Fprintf(w, "Bearer token is required") return } did := r.Header.Get("Authorization")[len(authBearer)+1:] if did == "" { fmt.Fprintf(w, "DID token is required") return } tk, err := token.NewToken(did) if err != nil { fmt.Fprintf(w, "Malformed DID token error: %s", err.Error()) return } if err := tk.Validate(); err != nil { fmt.Fprintf(w, "DID token failed validation: %s", err.Error()) return } return tk.GetIssuer()) }

GetPublicAddress

Gets the cryptographic public address of the Magic User who generated the supplied DID Token.

tk, err := token.NewToken("<DID_TOKEN>") if err != nil { log.Fatalf(err.Error()) } tk.GetPublicAddress()
Arguments

DID_TOKEN (string): A DID Token generated by a Magic user on the client-side.

Error

token.DIDTokenError if the given DID Token is malformed.

Returns

A public address of the Magic User who generated the DID Token.

Example

We are using Google AppEngine for an example below.

important

It is important to always validate the DID Token before using.

package main import ( "fmt" "log" "net/http" "os" "strings" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/token" ) const authBearer = "Bearer" func main() { http.HandleFunc("/v1/user/info", handler) port := os.Getenv("PORT") log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { if !strings.HasPrefix(r.Header.Get("Authorization"), authBearer) { fmt.Fprintf(w, "Bearer token is required") return } did := r.Header.Get("Authorization")[len(authBearer)+1:] if did == "" { fmt.Fprintf(w, "DID token is required") return } tk, err := token.NewToken(did) if err != nil { fmt.Fprintf(w, "Malformed DID token error: %s", err.Error()) return } if err := tk.Validate(); err != nil { fmt.Fprintf(w, "DID token failed validation: %s", err.Error()) return } return tk.GetPublicAddress()) }

Validate

Validates a DID token.

tk, err := token.NewToken("<DID_TOKEN>") if err != nil { log.Fatalf(err.Error()) } err = tk.Validate()
Arguments

DID_TOKEN (string): A DID Token generated by a Magic user on the client-side.

Error
  • token.DIDTokenError if the given DID Token is malformed.
Example

We are using Google AppEngine for an example below.

important

It is important to always validate the DID Token before using.

package main import ( "fmt" "log" "net/http" "os" "strings" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/token" ) const authBearer = "Bearer" func main() { http.HandleFunc("/v1/user/info", handler) port := os.Getenv("PORT") log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { if !strings.HasPrefix(r.Header.Get("Authorization"), authBearer) { fmt.Fprintf(w, "Bearer token is required") return } did := r.Header.Get("Authorization")[len(authBearer)+1:] if did == "" { fmt.Fprintf(w, "DID token is required") return } tk, err := token.NewToken(did) if err != nil { fmt.Fprintf(w, "Malformed DID token error: %s", err.Error()) return } if err := tk.Validate(); err != nil { fmt.Fprintf(w, "DID token failed validation: %s", err.Error()) return } return tk }

User Resource

The User resource and its methods are accessible on the Magic client instance by the User attribute. It provides methods to interact with Magic API.

m := client.New("<YOUR_API_SECRET_KEY>", magic.NewDefaultClient()) m.User m.User.GetMetadataByIssuer m.User.GetMetadataByPublicAddress m.User.GetMetadataByToken m.User.LogoutByIssuer m.User.LogoutByPublicAddress m.User.LogoutByToken

GetMetadataByIssuer

Retrieves information about the user by the supplied iss from the DID Token. This method is useful if you store the iss with your user data, which is recommended.

userInfo, err := m.User.GetMetadataByIssuer(issuer)
Arguments

issuer (string): The user's Decentralized ID, which can be parsed using Token.GetIssuer

Error
  • A magic.Error: In case of an error response from the Magic API, it will contain information about the error.
  • A magic.APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Returns
  • A [magic.UserInfo]: Contains all of the user meta information.
    • Issuer (string): The user's Decentralized ID.
    • Email (string): The user's email address.
    • PublicAddress (string): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
Example

We are using Google AppEngine for an example below.

package main import ( "fmt" "log" "net/http" "os" "strings" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/client" "github.com/magiclabs/magic-admin-go/token" ) const authBearer = "Bearer" func main() { http.HandleFunc("/v1/user/update", handler) port := os.Getenv("PORT") log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { m := client.New("<YOUR_API_SECRET_KEY>", magic.NewDefaultClient()) if !strings.HasPrefix(r.Header.Get("Authorization"), authBearer) { fmt.Fprintf(w, "Bearer token is required") return } did := r.Header.Get("Authorization")[len(authBearer)+1:] if did == "" { fmt.Fprintf(w, "DID token is required") return } tk, err := token.NewToken(did) if err != nil { fmt.Fprintf(w, "Malformed DID token error: %s", err.Error()) return } if err := tk.Validate(); err != nil { fmt.Fprintf(w, "DID token failed validation: %s", err.Error()) return } userInfo, err := m.User.GetMetadataByIssuer(tk.GetIssuer()) if err != nil { fmt.Fprintf(w, "Error: %s", err.Error()) return } return userInfo }

GetMetadataByPublicAddress

Retrieves information about the user by the supplied PublicAddress. This method is useful if you store the PublicAddress with your user data.

userInfo, err := User.GetMetadataByPublicAddress(publicAddress)
Arguments

publicAddress (string): The user's Ethereum public address, which can be parsed using Token.GetPublicAddress.

Error
  • A magic.Error: In case of an error response from the Magic API, it will contain information about the error.
  • A magic.APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Returns
  • A [magic.UserInfo]: Contains all of the user meta information.
    • Issuer (string): The user's Decentralized ID.
    • Email (string): The user's email address.
    • PublicAddress (string): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
Example

We are using Google AppEngine for an example below.

important

It is important to always validate the DID Token before using.

package main import ( "fmt" "log" "net/http" "os" "strings" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/client" "github.com/magiclabs/magic-admin-go/token" ) const authBearer = "Bearer" func main() { http.HandleFunc("/v1/user/update", handler) port := os.Getenv("PORT") log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { m := client.New("<YOUR_API_SECRET_KEY>", magic.NewDefaultClient()) if !strings.HasPrefix(r.Header.Get("Authorization"), authBearer) { fmt.Fprintf(w, "Bearer token is required") return } did := r.Header.Get("Authorization")[len(authBearer)+1:] if did == "" { fmt.Fprintf(w, "DID token is required") return } tk, err := token.NewToken(did) if err != nil { fmt.Fprintf(w, "Malformed DID token error: %s", err.Error()) return } if err := tk.Validate(); err != nil { fmt.Fprintf(w, "DID token failed validation: %s", err.Error()) return } userInfo, err := m.User.GetMetadataByPublicAddress(tk.GetPublicAddress()) if err != nil { fmt.Fprintf(w, "Error: %s", err.Error()) return } return userInfo }

GetMetadataByToken

Retrieves information about the user by the supplied DID Token.

userInfo, err := User.GetMetadataByToken(didToken)
Arguments

didToken (string): A DID Token generated by a Magic User on the client-side.

Error
  • A magic.Error: In case of an error response from the Magic API, it will contain information about the error.
  • A magic.APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Returns
  • A [magic.UserInfo]: Contains all of the user meta information.
    • Issuer (string): The user's Decentralized ID.
    • Email (string): The user's email address.
    • PublicAddress (string): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
Example

We are using Google AppEngine for an example below.

important

It is important to always validate the DID Token before using.

package main import ( "fmt" "log" "net/http" "os" "strings" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/client" ) const authBearer = "Bearer" func main() { http.HandleFunc("/v1/user/update", handler) port := os.Getenv("PORT") log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { m := client.New("<YOUR_API_SECRET_KEY>", magic.NewDefaultClient()) if !strings.HasPrefix(r.Header.Get("Authorization"), authBearer) { fmt.Fprintf(w, "Bearer token is required") return } did := r.Header.Get("Authorization")[len(authBearer)+1:] if did == "" { fmt.Fprintf(w, "DID token is required") return } tk, err := token.NewToken(did) if err != nil { fmt.Fprintf(w, "Malformed DID token error: %s", err.Error()) return } if err := tk.Validate(); err != nil { fmt.Fprintf(w, "DID token failed validation: %s", err.Error()) return } userInfo, err := m.User.GetMetadataByToken(did) if err != nil { fmt.Fprintf(w, "Error: %s", err.Error()) return } return userInfo }

LogoutByIssuer

Logs a user out of all Magic SDK sessions given the user's Decentralized ID (iss). This method is useful if you store the iss with your user data, which is recommended.

err := User.LogoutByIssuer(issuer)
Error
  • A magic.Error: In case of an error response from the Magic API, it will contain information about the error.
  • A magic.APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Arguments

issuer (string): The user's Decentralized ID, which can be parsed using Token.GetIssuer

Example

We are using Google AppEngine for an example below.

package main import ( "fmt" "log" "net/http" "os" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/client" ) func main() { http.HandleFunc("/v1/user/logout", handler) port := os.Getenv("PORT") log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { m := client.New("<YOUR_API_SECRET_KEY>", magic.NewDefaultClient()) // Use your logic to load user by user_id. userId := r.URL.Query().Get("user_id") user := logic.User.LoadById(userId) if tk.GetIssuer() != user.Issuer { fmt.Fprintf(w, "The request is not authorized.") return } err := m.User.LogoutByIssuer(user.Issuer) if err != nil { fmt.Fprintf(w, "Error: %s", err.Error()) return } }

LogoutByPublicAddress

Logs a user out of all Magic SDK sessions given the user's public address. This method is useful if you store the publicAddress .

err := User.LogoutByPublicAddress(publicAddress)
Arguments

publicAddress (string): The user's Ethereum public address.

Error
  • A magic.Error: In case of an error response from the Magic API, it will contain information about the error.
  • A magic.APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Example

We are using Google AppEngine for an example below.

package main import ( "fmt" "log" "net/http" "os" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/client" ) func main() { http.HandleFunc("/v1/user/logout", handler) port := os.Getenv("PORT") log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { m := client.New("<YOUR_API_SECRET_KEY>", magic.NewDefaultClient()) // User your logic to oad user by the user_id. userId := r.URL.Query().Get("user_id") user := logic.User.LoadById(userId) if tk.GetPublicAddress() != user.PublicAddress { fmt.Fprintf(w, "Request is not authorized.") return } err := m.User.LogoutByPublicAddress(user.PublicAddress) if err != nil { fmt.Fprintf(w, "Error: %s", err.Error()) return } }

LogoutByToken

Logs a user out of all Magic SDK sessions given the DID Token.

err := User.LogoutByToken(didToken)
Arguments

didToken (string): A DID Token generated by a Magic user on the client-side.

Error
  • A magic.Error: In case of an error response from the Magic API, it will contain information about the error.
  • A magic.APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Example

We are using Google AppEngine for an example below.

important

It is important to always validate the DID Token before using.

package main import ( "fmt" "log" "net/http" "os" "strings" "github.com/magiclabs/magic-admin-go" "github.com/magiclabs/magic-admin-go/client" "github.com/magiclabs/magic-admin-go/token" ) const authBearer = "Bearer" func main() { http.HandleFunc("/v1/user/logout", handler) port := os.Getenv("PORT") log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { m := client.New("<YOUR_API_SECRET_KEY>", magic.NewDefaultClient()) if !strings.HasPrefix(r.Header.Get("Authorization"), authBearer) { fmt.Fprintf(w, "Bearer token is required") return } did := r.Header.Get("Authorization")[len(authBearer)+1:] if did == "" { fmt.Fprintf(w, "DID token is required") return } tk, err := token.NewToken(did) if err != nil { fmt.Fprintf(w, "Malformed DID token error: %s", err.Error()) return } if err := tk.Validate(); err != nil { fmt.Fprintf(w, "DID token failed validation: %s", err.Error()) return } // Use your logic to load user by user_id. userId := r.URL.Query().Get("user_id") user := logic.User.LoadById(userId) if tk.GetIssuer() != user.Issuer { fmt.Fprintf(w, "Request is not authorized") return } err := m.User.LogoutByToken(did) if err != nil { fmt.Fprintf(w, "Error: %s", err.Error()) return } }

Error Handling

Errors

The conventional HTTP response is adopted by the SDK. For the status code in:

  • 2XX - Indicates success.
  • 4XX - Indicates client errors. Information provided to the SDK is invalid.
  • 5XX - Indicates server errors.

Magic Error

magic.Error is the base struct of all the API errors. You can check the error type to determine the API error accordingly.

_, err := // library call if err != nil { // Matching error by error type for a failed HTTP request. switch err.(type) { case (*magic.ForbiddenError): // Handle forbidden error. case (*magic.BadRequestError): // Handle bad request error. case (*magic.RateLimitingError): // Handle rate limiting error. case (*magic.AuthenticationError): // Handle authentication error. case (*magic.APIConnectionError): // Handle authentication error. default: fmt.Printf("Other HTTP request error: %v\n", err.Error()) } }
Http StatusCodeError TypeDescription
429magic.RateLimitingErrorToo many requests are submitted for a given period of time.
400magic.BadRequestErrorThe API requests might have missing required fields or bad inputs.
401magic.AuthenticationErrorThis means your API secret key is invalid.
403magic.ForbiddenErrorThis normally means the given API secret key doesn't have permission to perform the action on the given resources.
ā€“magic.APIErrorThis is a generic API error that handles other status codes that are not explicitly handled. Ex: 500 , 404 , etc.
ā€“magic.APIConnectionErrorNetwork connection error. This normally means the connection between your application and Magic API server cannot be established.