Sample codes of various programming languages are provided to demonstrate the general logic flow.
Generate the authentication signature. Signature should be set in header when connecting our API. For instance, we connect an API called "hello".
01
/First implement the signature generation function.
func MakeHMAC(nonce, path, secretKey string) string {
// Create a new HMAC by defining the hash type and the key (as byte array)
h := hmac.New(sha256.New, []byte(secretKey))
// Write Data to it
h.Write([]byte(nonce))
h.Write([]byte(path))
// Get result and encode as hexadecimal string
sha := hex.EncodeToString(h.Sum(nil))
fmt.Println("Result: " + sha)
return sha
}
02
/Set the request header when accessing the API.
// Generate a full URL
func GetFullUrl(base, path string) string {
var buffer bytes.Buffer
buffer.WriteString(base)
buffer.WriteString(path)
return buffer.String()
}
func GetApiExample(accessKey, secretKey, basePath, nonce string) {
helloPath := "/api/v1/hello"
// Generate a signature
signHello := MakeHMAC(nonce, helloPath, secretKey)
// Set headers and call the api
client := &http.Client{}
req, _ := http.NewRequest("GET", GetFullUrl(basePath, helloPath), nil)
req.Header.Set("nonce", nonce)
req.Header.Set("accessKey", accessKey)
req.Header.Set("signature", signHello)
res, err := client.Do(req)
// Output response
if err != nil {
fmt.Printf("The HTTP request failed with error %s\n", err)
} else {
data, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(data))
}
}
03
/Implement the main function and execute it.
import "strconv"
func main() {
fmt.Println("Starting the application...")
accessKey := "Your Access Key"
secretKey := "Your Secret Key"
BasePath := "https://translate.rozetta-api.io"
millis:= time.Now().UnixNano() / 1e6
nonce := strconv.FormatInt(millis, 10)
GetApiExample(accessKey, secretKey, BasePath, nonce)
fmt.Println("Terminating the application...")
}