Tutorials

Getting Started with the API

Get up and running on the Smartling API

In this tutorial, we'll set up and test API connectivity to Smartling by following these steps:

  1. Create a test project in your Smartling account
  2. Get access to the test project
  3. Obtain API credentials for the project
  4. Perform a round-trip test using the API:
    1. Set up environment
    2. Authenticate
    3. Upload a source file
    4. Download a translated file.

The first three steps above only need to be done once: when they're in place you can reuse them for your subsequent development work.

Step 1. Create a test project in Smartling

You need a test project in Smartling to test your integration during development. To create a test project, a user with Account Owner privileges in your Smartling account will need to perform the following steps:

  1. Log in to Smartling at https://dashboard.smartling.com
  2. Click on the Smartling logo in the upper-left corner to get to the Account Dashboard
  3. Click the Create New Project button
  4. Click on the Files tab of the Create Project dialog
  5. Select Resource Files (the default) and click Next
  6. Give your project a name indicating its purpose, e.g., 'API Testing'
  7. Don't select anything under Linguistic package; instead click the Create New Package link below it. This ensures that your project will get its own translation memory, and that your actions won’t affect other projects.
  8. Select a source language for the project, e.g., 'English'
  9. Select some target languages. These are the languages that you'll be translating into. For testing purposes, it's usually sufficient to have just two or three target languages.
    • Note: the sample code in this and other tutorials assumes 'French (France)' is one of the target languages, so make sure to include 'French (France)' in your choice of languages.
  10. Click the Create Project button.

Now that the project has been created, you will need to have access to it in the dashboard. 

Step 2. Get dashboard access to the test project

To use your test project for integration testing, you need to be granted Project Manager access to it. If you already have Account Owner access to Smartling, you automatically have access to the project, so you can skip this step.

If you have a Project Manager login to Smartling, but don't have access to the test project created above, a user with Account Owner access needs to grant you access by following these steps.  Make sure you are granted ‘Project Manager’ access to the project. The project should then be visible to you when you re-login to Smartling.

If you don't yet have a Smartling login, an Account Owner will need to create one for you by following these steps. Once this is done, you'll receive an email from Smartling containing a link to follow to complete the login creation process in your web browser. (Check your email spam folder if you don't see it.) Click on the link in the email and complete the login creation process. Once completed, you should see the Account Overview page with the projects you have access to. 

From the Account Overview page, click on the project to access it; or if you're in another project, select the test project from the Projects menu in the upper left.

Step 3. Obtain API credentials for the test project

API authentication credentials are required to use the Smartling API. You can get these by following these steps to create a V2 API token.

The data you need to access the project via API are:

  • Project ID
  • User Identifier
  • User Secret

The project ID and user identifier are always available from the API page, but the user secret is not, so you must keep a copy of it stored securely.

Step 4. Perform a 'round-trip' test using the API

For the round-trip test, we'll perform the following steps:

  1. Set up the environment
  2. Authenticate to the Smartling API
  3. Upload a file via API
  4. Download a 'translated' file via API.

1. Set up the environment

The authentication API call requires your API credentials, i.e., the user identifier and user secret. For security reasons, it’s recommended to make these values available as environment variables that can be accessed from your code, rather than storing them directly in your code. Since the project ID is used in API calls too, and is associated with the credentials, it's helpful to store it in an environment variable too.

Open a Terminal window (Mac/Linux) or command prompt (Windows) and enter the commands below to create the environment variables, replacing PROJECTID, USERIDENTIFIER and USERSECRET with the values obtained in Step 3 above.

export DEV_PROJECT_ID='PROJECTID'
export DEV_USER_IDENTIFIER='USERIDENTIFIER'
export DEV_USER_SECRET='USERSECRET'

set DEV_PROJECT_ID=PROJECTID
set DEV_USER_IDENTIFIER=USERIDENTIFIER
set DEV_USER_SECRET=USERSECRET

It’s helpful to store these commands in a script file, e.g., setenv.sh or setenv.cmd, which can be run when needed as follows:

source setenv.sh

.\setenv.cmd

 

In order to maintain control over your API credentials, ensure that you don't add the setenv script to your source control system.

Now that our authentication credentials are in place, we are ready to authenticate.

2. Authenticate

In the same terminal window or command prompt where you set the environment variables above, run the following command. Feel free to copy and paste it.

If using Python, you can start the Python interactive interpreter in the same terminal (via python or python3 on Mac or Linux, and py on Windows). This launches the interpreter presenting a >>> prompt where you can enter python code. You will need to press Enter one or more times until the >>> prompt reappears after pasting the code samples into your interpreter window. Note: you may need to install the 'requests' python package, which the sample code uses.

curl --silent \
--request POST \
--header "Content-Type: application/json" \
--data "{\"userIdentifier\": \"$DEV_USER_IDENTIFIER\", \
\"userSecret\": \"$DEV_USER_SECRET\"}" \
"https://api.smartling.com/auth-api/v2/authenticate"

curl --silent --request POST --header "Content-Type: application/json" --data "{\"userIdentifier\": \"%DEV_USER_IDENTIFIER%\", \"userSecret\": \"%DEV_USER_SECRET%\"}" https://api.smartling.com/auth-api/v2/authenticate

import sys
import os
import requests
import json

# Read authentication credentials from environment
user_id = os.environ.get('DEV_USER_IDENTIFIER')
user_secret = os.environ.get('DEV_USER_SECRET')
project_id = os.environ.get('DEV_PROJECT_ID')

# Authenticate
api_url = 'https://api.smartling.com/auth-api/v2/authenticate'
api_parameters = {
    'userIdentifier': user_id,
    'userSecret': user_secret
}
api_response = requests.post(api_url, json = api_parameters)
        
# Store access token for use in subsequent API calls    
access_token = api_response.json()['response']['data']['accessToken']

If authentication is successful, it will result in a response like the following (except with much longer token values) being printed to the terminal window:

{"response":{"code":"SUCCESS","data":{"accessToken":"VERYLONGSEQUENCEOFCHARACTERSTOCOPY","refreshToken":"VERYLONGSEQUENCEOFCHARACTERS","expiresIn":480,"refreshExpiresIn":21600,"tokenType":"Bearer"}}}

If you get an error response, re-check the previous steps and try again.

Now, copy the value of the access token received in the response above into an environment variable so that we can re-use it in our next steps. The access token is the very long value in quotes after "accessToken": in the response. Make sure not to copy the refresh token which looks similar and appears in the response directly after the access token value.

If you used Python, you don't need to copy the access token because the value is automatically stored in a variable by the code. However, you do need to leave the same Python interpreter running so that the variable value is preserved for later usage.

Once you've copied the access token from the response, save it in an environment variable as follows (substituting in your copied access token value):

export sltoken='VERYLONGSEQUENCEOFCHARACTERSTOCOPY'

set sltoken=VERYLONGSEQUENCEOFCHARACTERSTOCOPY

3. Upload a test file using the API

Most API integrations with Smartling are based on uploading files for translation and downloading translated versions of these files.

For this test, create a file named strings.json in the directory where you are executing the test, and populate it with the content below:

strings.json

{
    "app.home.label" : "Home",
    "app.button.submit.label" : "Submit"
}

Then run the following command or script code:

curl --request POST \
     --header "Authorization: Bearer $sltoken" \
     --form "file=@strings.json;type=text/plain" \
     --form "fileUri=strings.json" \
     --form "fileType=json" \
     "https://api.smartling.com/files-api/v2/projects/$DEV_PROJECT_ID/file"

curl --request POST --header "Authorization: Bearer %sltoken%" --form "file=@strings.json;type=text/plain" --form "fileUri=strings.json" --form "fileType=json" "https://api.smartling.com/files-api/v2/projects/%DEV_PROJECT_ID%/file"

file_name = 'strings.json'
api_url = 'https://api.smartling.com/files-api/v2/projects/' + project_id + '/file'
api_request_headers = {'Authorization': 'Bearer ' + access_token}
api_parameters = {
    'fileUri': file_name,
    'fileType': 'json'
}
file_to_upload = {
    'file': open(file_name, 'rb')
}
api_response = requests.post(api_url,
                        headers = api_request_headers,
                        data = api_parameters,
                        files = file_to_upload)

# Check if the upload was successful
if api_response.status_code in [200, 202]:
    print('Uploaded ' + file_name)
else:
    print(api_response.text)

 

If you're running the curl command, you should get a response like the following:

{"response":{"code":"SUCCESS","data":{"wordCount":2,"stringCount":2,"overWritten":false}}}

If instead you get a response like the one below, it means that your access token expired.

{"response":{"code":"AUTHENTICATION_ERROR","errors":[{"key":null,"message":"Unable to authenticate bearer token","details":null}]}}

Access tokens expire after five minutes and need to be refreshed via a separate API call. For now, however, simply re-run the authentication step above and try again.

Once you receive a successful response, you can confirm the results in the Smartling dashboard:

  1. Login to Smartling at https://dashboard.smartling.com
  2. If you're not in your test project, navigate to it by either clicking on it from the Account dashboard, or selecting it from the Projects menu in the upper left.
  3. Click on the Files tab.

You should see the file you just uploaded, i.e., strings.json, in the list.

 

file_list.png

 

If you click on the file, and then click on the source language, you'll be taken to a view of the strings that were parsed from the file for translation.

A manual way to achieve what we just did via API is to drag a file into the Files tab in the dashboard. This approach is often useful in testing. Try it now by making a copy of your test file and dragging it into the Files tab.

4. Download a 'translated' file from Smartling

For this test, we'll download pseudo translations of the uploaded file. Pseudo translations simply replace the translatable content with a slightly lengthened version of the string with some characters accented. When your application is built with pseudo translations, you can quickly spot any untranslated strings (for example, a hard-coded string in your application that should be externalized), as well as layout problems caused by the longer strings.

For our purposes, pseudo translations allow us to download a 'translated' file without having to manually translate the content or configure machine translation.

Run the following command or script code:

curl --get \
     --header "Authorization: Bearer $sltoken" \
     --output "strings_pseudo.json" \
     --data-urlencode "fileUri=strings.json" \
     --data-urlencode "retrievalType=pseudo" \
     "https://api.smartling.com/files-api/v2/projects/$DEV_PROJECT_ID/locales/fr-FR/file"

curl --get --header "Authorization: Bearer %sltoken%" --output "strings_pseudo.json" --data-urlencode "fileUri=strings.json" --data-urlencode "retrievalType=pseudo" "https://api.smartling.com/files-api/v2/projects/%DEV_PROJECT_ID%/locales/fr-FR/file"

# Download pseudo-translated file
# we need to use a valid locale ID from the test project in the API URL
locale_id = 'fr-FR' 

api_url = 'https://api.smartling.com/files-api/v2/projects/' + project_id + '/locales/' + locale_id + '/file'
api_request_headers = {'Authorization': 'Bearer ' + access_token}
api_parameters = {
    'fileUri': file_name,
    'retrievalType': 'pseudo'
}
api_response = requests.get(api_url,
                            headers=api_request_headers,
                            params=api_parameters)

# If successful, write the file to disk
if api_response.status_code == 200:
    with open('strings_pseudo.json', 'wb') as f:
f.write(api_response.content) else: print(api_response.text)

This should result in a file named strings_pseudo.json being downloaded to your current directory containing the content below:

{
       "app.home.label" : "[H~ómé]",
       "app.button.submit.label" : "[S~úbm~ít]"
}

Note that the original strings have been replaced by pseudo translations. This is the standard method that Smartling uses for file translations: i.e., the translated file is in the same format as the uploaded source file, except that the translatable source strings are replaced with the corresponding translations.

Summary

In this tutorial, we established the prerequisites for API work with Smartling: a test project with project-manager access, and an API token. These can be reused in the next tutorial and your subsequent development work. We also tested them by uploading a file via API and downloading a pseudo-translated version of the file.

Working examples in Python and Java illustrating these topics can be found in GitHub here: Getting Started examples.

Next steps

The next tutorial covers a more realistic use of the APIs for translating files by using translation jobs and workflows.

 

Was this article helpful?