Examples
Our GraphiQL documentation provides basically all the information you need to start using our API, but we know that sometimes it's easier to have some examples to start with. Here are some examples of code to connect, and get the list of assets available in your Layrz account.
Login procedure
Locate in Layrz API is simple, you just need or a current API token, or the user and password. For our example, we will use the 1st option, let's look at some examples in several programming languages
py
"""
PIP dependencies:
pip install graphql_client
"""
from graphql_client import GraphQLClient
# Initialize the client
client = GraphQLClient(endpoint='https://api.layrz.com/graphql')
# Perform the mutation and send the required variables
response = client.query(
"""
mutation($username: String!, $password: String!) {
login(username: $username, password: $password) {
status
errors
result {
id
name
token {
validBefore
token
}
}
}
}
""",
{
'username': 'your-username',
'password': 'your-password'
}
)
result = response['data']['login']
# Check the response status
if result['status'] == 'OK':
# Print the result
token = result['result']['token']['token']
print(f"Your token: {token}")
else:
# Print the error
print(f"Login error: {result['errors']}")
rb
=begin
RubyGems dependencies:
gem install graphql-client
=end
require "graphql/client"
require "graphql/client/http"
# Initialize the GraphQL HTTP client
HTTP = GraphQL::Client::HTTP.new("https://api.layrz.com/graphql")
# Load the schema
Schema = GraphQL::Client.load_schema(HTTP)
# Initialize the GraphQL client
Client = GraphQL::Client.new(schema: Schema, execute: HTTP)
# Define the mutation
LoginMutation = Client.parse <<-'GRAPHQL'
mutation($username: String!, $password: String!) {
login(username: $username, password: $password) {
status
errors
result {
id
name
token {
validBefore
token
}
}
}
}
GRAPHQL
# Perform the mutation and send the required variables
response = Client.query(
LoginMutation,
variables: {
username: "your-username",
password: "your-password"
}
)
# Check the response status
if response.data.login.status == 'OK'
# Print the result
token = response.data.login.result.token.token
puts "Your token: #{token}"
else
# Print the error
puts "Login Error #{response.data.login.errors}"
end
php
<?php
/*
Composer dependencies
composer require gmostafa/php-graphql-client
*/
require_once __DIR__ . '/./vendor/autoload.php';
use GraphQL\Client;
use GraphQL\Exception\QueryError;
use GraphQL\Mutation;
use GraphQL\Variable;
use GraphQL\Query;
$client = new Client(
'https://api.layrz.com/graphql'
);
$gql = (new Mutation('login'))
->setVariables([
new Variable('username', 'String', true),
new Variable('password', 'String', true)
])
->setArguments([
'username' => '$username',
'password' => '$password'
])
->setSelectionSet([
'status',
'errors',
(new Query('result'))
->setSelectionSet([
'id',
'name',
(new Query('token'))
->setSelectionSet([
'token'
])
])
]);
$variables = [
"username" => "your-username",
"password" => "your-password"
];
$response = $client->runQuery($gql, true, $variables);
$loginRes = $response->getData()['login'];
if ($loginRes['status'] == "OK") {
$token = $loginRes['result']['token']['token'];
echo "Your token: " . $token;
} else {
echo "Login Error: " . json_encode($loginRes['errors']);
}
go
/*
Package dependencies:
go get github.com/hasura/go-graphql-client
*/
package main
import (
"context"
"fmt"
graphql "github.com/hasura/go-graphql-client"
)
func main() {
var mutation struct {
Login struct {
Status graphql.String
Errors interface{} `graphql:"errors"`
Result struct {
Id graphql.ID `graphql:"id"`
Name graphql.String `graphql:"name"`
Token struct {
Token graphql.String `graphql:"token"`
} `graphql:"token"`
} `graphql:"result"`
} `graphql:"login(username: $username, password: $password)"`
}
client := graphql.NewClient("https://api.layrz.com/graphql", nil)
variables := map[string]interface{}{
"username": graphql.String("your-username"),
"password": graphql.String("your-password"),
}
client.Mutate(context.Background(), &mutation, variables)
if mutation.Login.Status == "OK" {
fmt.Println("Your token: ", mutation.Login.Result.Token.Token)
} else {
fmt.Println("Login Errors: ", mutation.Login.Errors)
}
}
dart
/*
Dart dependencies:
dart pub add graphql
Flutter dependencies:
flutter pub add graphql
*/
import 'package:graphql/client.dart';
void main() async {
// Initialize the client
final client = GraphQLClient(
cache: GraphQLCache(
partialDataPolicy: PartialDataCachePolicy.accept,
),
link: HttpLink("https://api.layrz.com/graphql"),
defaultPolicies: DefaultPolicies(
query: Policies(
fetch: FetchPolicy.noCache,
),
mutate: Policies(
fetch: FetchPolicy.noCache,
),
),
);
// Perform the mutation and send the required variables
final QueryResult response = await client.mutate(
MutationOptions(
document: gql(r'''
mutation($username: String!, $password: String!) {
login(username: $username, password: $password) {
status
errors
result {
id
name
token {
token
validBefore
}
}
}
}
'''),
variables: {
'username': 'your-username',
'password': 'your-password',
},
),
);
if (response.hasException) { // Validate if has exception
print("login() exception: \${response.exception.toString()}");
} else if (response.data == null) { // Validate if the response is null
print("login() has issues: No data received");
} else { // Handle a valid response
final login = response.data['login'];
// Check the response status
if (login['status'] == 'OK') {
String token = login['result']['token']['token'];
print("Your token: $token");
} else {
// Handle the errors
print("login() error: \${login['errors']}");
}
}
}
cs
/*
dotnet dependencies:
dotnet add package GraphQL
dotnet add package GraphQL.Client
dotnet add package GraphQL.Client.Serializer.Newtonsoft
*/
using System;
using GraphQL;
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;
namespace MyApp
{
// Token entity definition
public class TokenType
{
public string? Token { get; set; } // Your token
}
// User entity definition
public class UserType
{
public string? Id { get; set; }
public string? Name { get; set; }
public TokenType? Token { get; set; }
}
// Mutation rsponse definition
public class LoginResponseType
{
public string? Status { get; set; }
public UserType? Result { get; set; }
}
// Mutation entity definition
public class LoginMutationResponseType
{
public LoginResponseType? Login { get; set; }
}
class Program
{
static async Task Main(string[] args)
{
var client = new GraphQLHttpClient("https://api.layrz.com/graphql", new NewtonsoftJsonSerializer());
GraphQLRequest request = new GraphQLRequest
{
Query = @"
mutation($username: String!, $password: String!) {
login(username: $username, password: $password) {
status
errors
result {
id
name
token {
token
}
}
}
}
",
Variables = new {
username = "your-username",
password = "your-password"
},
};
try {
var response = await client.SendMutationAsync<LoginMutationResponseType>(request);
var loginResp = response.Data.Login;
if (loginResp?.Status == "OK") {
string token = loginResp!.Result!.Token!.Token!;
Console.WriteLine($"Your token: {token}");
} else {
Console.WriteLine("Login failed");
}
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}
}
Get Assets
Do you need the list of assets? No problem, we have a query for it! It is very simple to use, let's see the examples in the different languages
py
"""
PIP dependencies:
pip install graphql_client
"""
from graphql_client import GraphQLClient
# Initialize the client
client = GraphQLClient(endpoint='https://api.layrz.com/graphql')
# Perform the query and send the required variables
response = client.query("""
query($apiToken: String!) {
assets(apiToken: $apiToken) {
status
errors
result {
id
name
primary {
id
name
ident
}
devices {
id
name
ident
}
}
}
}
""", {'apiToken': 'your-api-token'})
result = response['data']['assets']
# Check the response status
if result['status'] == 'OK':
# Print the result
assets = result['result']
print(f"Your assets: {assets}")
else:
# Print the error
print(f"Assets error: {result['errors']}")
rb
=begin
RubyGems dependencies:
gem install graphql-client
=end
require "graphql/client"
require "graphql/client/http"
# Initialize the GraphQL HTTP client
HTTP = GraphQL::Client::HTTP.new("https://api.layrz.com/graphql")
# Load the schema
Schema = GraphQL::Client.load_schema(HTTP)
# Initialize the GraphQL client
Client = GraphQL::Client.new(schema: Schema, execute: HTTP)
# Define the query
AssetsQuery = Client.parse <<-'GRAPHQL'
query($apiToken: String!) {
assets(apiToken: $apiToken) {
status
errors
result {
id
name
primary {
id
name
ident
}
devices {
id
name
ident
}
}
}
}
GRAPHQL
# Perform the query and send the required variables
response = Client.query(
AssetsQuery,
variables: {
apiToken: "your-api-token"
}
)
# Check the response status
if response.data.assets.status == 'OK'
# Print the result
assets = response.data.assets.result
puts "Your assets: #{assets}"
else
# Print the error
puts "Assets Error: #{response.data.login.errors}"
end
php
<?php
/*
Composer dependencies
composer require gmostafa/php-graphql-client
*/
require_once __DIR__ . '/./vendor/autoload.php';
use GraphQL\Client;
use GraphQL\Exception\QueryError;
use GraphQL\Mutation;
use GraphQL\Variable;
use GraphQL\Query;
$client = new Client(
'https://api.layrz.com/graphql'
);
$gql = (new Query('assets'))
->setVariables([
new Variable('apiToken', 'String', true)
])
->setArguments([
'apiToken' => '$apiToken'
])
->setSelectionSet([
'status',
'errors',
(new Query('result'))
->setSelectionSet([
'id',
'name',
(new Query('primary'))
->setSelectionSet([
'id',
'name',
'ident'
]),
(new Query('devices'))
->setSelectionSet([
'id',
'name',
'ident'
])
])
]);
$variables = [
"apiToken" => "your-api-token"
];
$response = $client->runQuery($gql, true, $variables);
$assetsRes = $response->getData()['assets'];
if ($assetsRes['status'] == "OK") {
$assets = $assetsRes['result'];
echo "Your assets: " . json_encode($assets);
} else {
echo "assets Error: " . json_encode($assetsRes['errors']);
}
go
/*
Package dependencies:
go get github.com/hasura/go-graphql-client
*/
package main
import (
"context"
"fmt"
graphql "github.com/hasura/go-graphql-client"
)
type Device struct {
Id graphql.ID `graphql:"id"`
Name graphql.String `graphql:"name"`
Ident graphql.String `graphql:"ident"`
}
func main() {
var query struct {
Assets struct {
Status graphql.String
Errors interface{} `graphql:"errors"`
Result []struct {
Id graphql.ID `graphql:"id"`
Name graphql.String `graphql:"name"`
primary Device `graphql:"primary"`
devices []Device `graphql:"devices"`
} `graphql:"result"`
} `graphql:"assets(apiToken: $apiToken)"`
}
client := graphql.NewClient("https://api.layrz.com/graphql", nil)
variables := map[string]interface{}{
"apiToken": graphql.String("your-api-token"),
}
client.Query(context.Background(), &query, variables)
if query.Assets.Status == "OK" {
fmt.Println("Your assets: ", query.Assets.Result)
} else {
fmt.Println("Assets Errors: ", query.Assets.Errors)
}
}
dart
/*
Dart dependencies:
dart pub add graphql
Flutter dependencies:
flutter pub add graphql
*/
import 'package:graphql/client.dart';
void main() async {
// Initialize the client
final client = GraphQLClient(
cache: GraphQLCache(
partialDataPolicy: PartialDataCachePolicy.accept,
),
link: HttpLink("https://api.layrz.com/graphql"),
defaultPolicies: DefaultPolicies(
query: Policies(
fetch: FetchPolicy.noCache,
),
mutate: Policies(
fetch: FetchPolicy.noCache,
),
),
);
// Perform the query and send the required variables
final QueryResult response = await client.mutate(
MutationOptions(
document: gql(r'''
query($apiToken: String!) {
assets(apiToken: $apiToken) {
status
errors
result {
id
name
primary {
id
name
ident
}
devices {
id
name
ident
}
}
}
}
'''),
variables: {
'apiToken': 'your-api-token',
},
),
);
if (response.hasException) { // Validate if has exception
print("assets() exception: \${response.exception.toString()}");
} else if (response.data == null) { // Validate if the response is null
print("assets() has issues: No data received");
} else { // Handle a valid response
final assetsResp = response.data['assets'];
// Check the response status
if (assetsResp['status'] == 'OK') {
List<dynamic> assets = assetsResp['result'];
print("Your assets: $assets");
} else {
// Handle the errors
print("assets() error: \${assetsResp['errors']}");
}
}
}
cs
/*
dotnet dependencies:
dotnet add package GraphQL
dotnet add package GraphQL.Client
dotnet add package GraphQL.Client.Serializer.Newtonsoft
*/
using System;
using GraphQL;
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;
namespace MyApp
{
// Token entity definition
public class DeviceType
{
public string? Id { get; set; }
public string? Name { get; set; }
public string? Ident { get; set; }
}
// User entity definition
public class AssetType
{
public string? Id { get; set; }
public string? Name { get; set; }
public DeviceType? Primary { get; set; }
public List<DeviceType>? Devices { get; set; }
}
// Mutation rsponse definition
public class AssetsResponseType
{
public string? Status { get; set; }
public List<AssetType>? Result { get; set; }
}
// Mutation entity definition
public class AssetsQueryResponseType
{
public AssetsResponseType? Assets { get; set; }
}
class Program
{
static async Task Main(string[] args)
{
var client = new GraphQLHttpClient("https://api.layrz.com/graphql", new NewtonsoftJsonSerializer());
GraphQLRequest request = new GraphQLRequest
{
Query = @"
query($apiToken: String!) {
assets(apiToken: $apiToken) {
status
errors
result {
id
name
primary {
id
name
ident
}
devices {
id
name
ident
}
}
}
}
",
Variables = new {
apiToken = "your-api-token"
},
};
try {
var response = await client.SendQueryAsync<AssetsQueryResponseType>(request);
var assetsResp = response.Data.Assets;
if (assetsResp?.Status == "OK") {
var assets = assetsResp!.Result!;
Console.WriteLine($"Your assets: {assets}");
} else {
Console.WriteLine("Assets failed");
}
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}
}