Getting started with Vantage¶
The Python Lokalise SDK supports the
Lokalise Vantage API
through the ClientVantage class.
The Vantage API provides a different resource model from the Expert API. It has its own endpoints, response structures, pagination mechanism, and error handling. Both APIs are available through the same Python package, but use separate client classes.
Note
Use ClientVantage for Lokalise Vantage projects.
For Lokalise Expert projects, use the regular Client
or OAuthClient.
Installation and requirements¶
Install the Python Lokalise SDK using pip:
pip install python-lokalise-api
If you already have the SDK installed, upgrade to a version that supports the Vantage API:
pip install --upgrade python-lokalise-api
Initializing the client¶
To send Vantage API requests, you need a personal Lokalise API token. You can generate one in your Lokalise profile settings, under API tokens.
Vantage uses the same personal API tokens as the Expert API. For more information, refer to the Vantage API authentication documentation.
Import the SDK and create a client:
import lokalise
client = lokalise.ClientVantage("YOUR_API_TOKEN")
We recommend storing your API token in an environment variable rather than hardcoding it in your application:
import os
from lokalise import ClientVantage
client = ClientVantage(os.environ["LOKALISE_VANTAGE_API_TOKEN"])
You can now use the client to retrieve Vantage resources. For example, fetch the content units of a project item:
units = client.content_units("project-id", "item-id")
for unit in units:
print(unit.key)
print(unit.source_segments_count)
Client configuration¶
The client accepts the following optional configuration parameters:
connect_timeout- connection timeout in seconds. Defaults toNone(no explicit timeout).read_timeout- read timeout in seconds. Defaults toNone(no explicit timeout).enable_compression- whether to enable gzip and deflate compression for API responses. Defaults toFalse.api_host- custom API base URL. Defaults tohttps://api.lokalise.com/vantage/v1/.
For example:
client = lokalise.ClientVantage(
"YOUR_API_TOKEN",
connect_timeout=5,
read_timeout=30,
enable_compression=True,
)
Client configuration can also be changed after initialization:
client.connect_timeout = 10
client.read_timeout = 60
client.enable_compression = True
When specifying a custom API host, provide the complete base URL, including the API path prefix:
client = lokalise.ClientVantage(
"YOUR_API_TOKEN",
api_host="https://example.com/vantage/v1/",
)
Objects and models¶
Individual Vantage resources are represented as Python model objects. The SDK maps camelCase fields returned by the API to snake_case Python attributes.
For example, the API fields projectId and sourceSegmentsCount
are exposed as project_id and source_segments_count,
respectively.
units = client.content_units("project-id", "item-id")
if units:
unit = units[0]
print(unit.id)
print(unit.project_id)
print(unit.key)
print(unit.source_segments_count)
To access the original resource data without attribute name conversion,
use the raw_data attribute:
print(unit.raw_data)
print(unit.raw_data["sourceSegmentsCount"])
Model attributes that are absent from the API response are set to
None.
Vantage models also expose a warnings attribute.
When a response for an individual resource contains warnings,
the SDK makes them available through this attribute.
Otherwise, it contains an empty list.
Collections of resources¶
Methods that retrieve multiple resources return collection objects. Each collection contains individual resource models and supports the standard Python sequence operations.
For example:
units = client.content_units("project-id", "item-id")
len(units) # Number of loaded resources
units.items # List of resource models
units[0] # First resource, if available
units[-1] # Last resource, if available
units[:3] # List containing up to three resources
You can iterate over a collection directly without accessing
the items attribute:
for unit in units:
print(unit.id, unit.key)
The collection contains only the resources returned by the current API request. Additional pages are not fetched automatically.
Cursor pagination¶
Vantage list endpoints use cursor-based pagination. Unlike offset-based pagination, you do not specify a page number. Instead, you request another batch of resources using a cursor provided by the previous response.
For more information, refer to the Vantage API pagination documentation.
To control the maximum number of resources returned in a single
response, use the limit parameter:
units = client.content_units(
"project-id",
"item-id",
params={"limit": 100},
)
Paginated Vantage collections expose the following attributes:
meta_count- number of resources reported by the API for the current response.cursor- cursor returned by the API.next_cursor- alias for the returned cursor.has_more- whether additional results are available.
Collections also provide the following pagination methods:
has_next_page()- whether another page is available.has_next_cursor()- whether another page is available and a cursor is present.is_last_page()- whether the current page is the final page.
For example:
print(units.meta_count)
print(units.cursor)
print(units.has_more)
if units.has_next_page():
next_page = client.content_units(
"project-id",
"item-id",
params={
"limit": 100,
"after": units.cursor,
},
)
Note
A cursor may be present even on the final page.
Always check has_more or has_next_page() before
requesting additional results.
To retrieve all available content units, continue requesting pages until there are no more results:
project_id = "project-id"
item_id = "item-id"
params = {"limit": 100}
while True:
units = client.content_units(
project_id,
item_id,
params=params,
)
for unit in units:
print(unit.key)
if not units.has_next_page():
break
params = {
"limit": 100,
"after": units.cursor,
}
Cursor values should be treated as opaque strings. Pass them back to the API without modifying or decoding them.
The supported pagination parameters and maximum page size may vary by endpoint. Refer to the corresponding API endpoint documentation for specific requirements.
Error handling¶
Vantage API errors are represented by exceptions defined in
lokalise.errors.vantage.
Unlike Expert API exceptions, Vantage exceptions are not represented
by separate classes for individual HTTP status codes.
Instead, the SDK exposes the error code returned by the API
through the code attribute.
For more information about the API error format, refer to the Vantage API error documentation.
Single errors¶
When an API request fails, the SDK raises a VantageError exception.
The exception provides the following attributes:
message- human-readable error message.code- machine-readable error code returned by the API.status_code- HTTP response status code.details- additional error information, if available.validation_errors- extracted validation issues, if available.
For example:
from lokalise.errors.vantage import VantageError
try:
units = client.content_units(
"invalid-project-id",
"invalid-item-id",
)
except VantageError as exc:
print(exc.message)
print(exc.code)
print(exc.status_code)
print(exc.details)
To obtain a formatted message containing the error code and
additional details, use detailed_message():
try:
units = client.content_units(
"invalid-project-id",
"invalid-item-id",
)
except VantageError as exc:
print(exc.detailed_message())
If the API returns an error response in an unexpected format,
the SDK raises a VantageError with the unknown_error code.
Multiple errors¶
The Vantage API can return several errors in a single response.
In this case, the SDK raises an AggregateError exception.
An aggregate exception contains individual VantageError instances
accessible through its errors attribute.
from lokalise.errors.vantage import AggregateError, VantageError
try:
units = client.content_units(
"invalid-project-id",
"invalid-item-id",
)
except AggregateError as exc:
print(exc.status_code)
for error in exc.errors:
print(error.detailed_message())
except VantageError as exc:
print(exc.detailed_message())
AggregateError inherits from VantageError.
Therefore, catching VantageError also handles aggregate exceptions.
If you want to handle aggregate exceptions separately, catch
AggregateError before VantageError.
Validation errors¶
When a validation error contains structured validation issues in
a supported format, the SDK extracts them into the
validation_errors attribute.
Each validation issue may contain the following fields:
keyword- validation rule that failed.instancePath- location of the invalid value.schemaPath- location of the corresponding validation rule.params- additional validation parameters.message- optional description of the validation issue.
For example:
def print_validation_errors(error: VantageError) -> None:
for issue in error.validation_errors or []:
print(issue["instancePath"])
print(issue.get("message"))
The validation_errors attribute is None when structured
validation information is unavailable.
For aggregate exceptions, inspect the validation issues of each individual error.
Handling errors across both APIs¶
Expert and Vantage API exceptions inherit from the common
ClientError base exception.
If your application uses both APIs, you can catch SDK-specific exceptions without depending on a particular API error format:
from lokalise.errors.base import ClientError
try:
units = client.content_units("project-id", "item-id")
except ClientError as exc:
print(exc)
Note that network failures and invalid local arguments may raise
other exceptions that do not inherit from ClientError.