Go SDK Quickstart
Following the steps described on this page, you'll create a simple Go application that interacts with the Fatture in Cloud API.
If you want to download the complete working example you can find it here.
0️⃣ Prerequisites
In this guide, we assume that these prerequisites are met:
- Go installed
- A private app using the OAuth 2.0 Authorization Code Flow
- A Fatture in Cloud account.
1️⃣ Step One: Install the Fatture in Cloud SDK
In this quickstart, we'll use the Fatture in Cloud SDK.
To install it:
go get github.com/fattureincloud/fattureincloud-go-sdk
2️⃣ Step Two: Set up the OAuth access token retrieval
Create the file oauth.go and copy in the following code:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
oauth "github.com/fattureincloud/fattureincloud-go-sdk/v2/oauth2"
)
func getOAuthAccessToken(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
auth := oauth.NewOAuth2AuthorizationCodeManager("CLIENT_ID", "CLIENT_SECRET", "http://localhost:8000/oauth")
if query.Get("code") == "" {
http.Redirect(w, r, auth.GetAuthorizationUrl([]oauth.Scope{oauth.Scopes.ENTITY_SUPPLIERS_READ}, "EXAMPLE_STATE"), http.StatusFound)
} else {
code := query.Get("code")
token, err := auth.FetchToken(code)
if err != nil {
log.Println("Error on response.\n[ERROR] -", err)
http.Error(w, "500 internal server error.", http.StatusInternalServerError)
return
}
jsonObj, _ := json.Marshal(token)
// saving the oAuth access token in the token.json file
err = ioutil.WriteFile("token.json", jsonObj, 0644)
if err != nil {
log.Println("Error on writing the file.\n[ERROR] -", err)
http.Error(w, "500 internal server error.", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Token succesfully retrived and stored in token.json")
}
}
To make this code work properly the only thing you need to set your client id, client secret and eventually the redirect uri at line 15.
In this QuickStart the access token and refresh token are stored in a file. This is only for educational purposes, the OAuth access token and refresh token are sensitive data and should be saved securely on your database. Also, never share your Client Secret with third-party actors, or publish it to your frontend!
4️⃣ Step Four: Set up the sample
In this example, we'll show how to retrieve your Company ID using the Go SDK. If you plan to manage only one company, you can insert it directly into your code as a variable. Check the Company-scoped Methods page for more info.
Create the files main.go and quickstart.go in your working directory and copy in the following code:
- main.go
- quickstart.go
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/oauth", getOAuthAccessToken)
http.HandleFunc("/quickstart", getFirstCompanySuppliers)
fmt.Printf("Starting server at port 8000\n")
if err := http.ListenAndServe(":8000", nil); err != nil {
log.Fatal(err)
}
}
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
fattureincloudapi "github.com/fattureincloud/fattureincloud-go-sdk/v2/api"
oauth "github.com/fattureincloud/fattureincloud-go-sdk/v2/oauth2"
)
func getFirstCompanySuppliers(w http.ResponseWriter, r *http.Request) {
rawData, err := os.ReadFile("token.json")
if err != nil {
fmt.Println(err)
}
tokenObj := oauth.OAuth2AuthorizationCodeTokenResponse{}
json.Unmarshal(rawData, &tokenObj)
accessToken := tokenObj.AccessToken
// Configure OAuth2 access token for authorization:
auth := context.WithValue(context.Background(), fattureincloudapi.ContextAccessToken, accessToken)
configuration := fattureincloudapi.NewConfiguration()
apiClient := fattureincloudapi.NewAPIClient(configuration)
// Retrieve the first company id
userCompaniesResponse, _, err := apiClient.UserAPI.ListUserCompanies(auth).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.ListUserCompanies``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
http.Error(w, "500 internal server error.", http.StatusInternalServerError)
return
}
firstCompanyId := userCompaniesResponse.GetData().Companies[0].GetId()
// Retrieve the list of the Suppliers
companySuppliers, _, err := apiClient.SuppliersAPI.ListSuppliers(auth, firstCompanyId).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.ListSuppliers``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
http.Error(w, "500 internal server error.", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(companySuppliers)
}
Make sure your FattureInCloud app redirect URL points at the just edited file (e.g. http://localhost:8000/oauth).
5️⃣ Step Five: Run the sample
From the command line, run the following command:
go run .
Now visit http://localhost:8000/oauth (or whatever your URL is), you will be redirected to the Fatture in Cloud login page where you will be asked to grant some permissions, according to what scopes you specified previously. Finally, you will see the success message and the access token will be stored in the token.json file.
You can now visit http://localhost:8000/quickstart (or whatever your URL is) to test the application.
❓ What now?
In this example, we used a limited set of the available API methods to show how to use our SDK.
If you want to access the full documentation of the available methods and models, you can check the following resources:
- Go SDK GitHub Repository: the Readme file contains the full list of the available methods and models
- API Reference: it contains the list of methods and models
- OpenAPI Specification: Our OpenAPI Specification contains the full description of the available methods and models
- Go pkg page: The main package page on GoPkg