Call any endpoint of the API
Reach an endpoint that the hand-written SDK does not wrap: with the generated client in JavaScript and Python, and with the request method of the SDK in PHP, Java and C#.
What it shows
- The SDK gives you a client for the whole API, already set up with your base URL and API key.
- The program calls an Admin API endpoint that the hand-written SDK has no method for: the list of users, with a search text and a sort order.
- It reads the answer as typed data: each user, and the
paginationobject. - It asks for the next page until
hasNextPageis false.
Each language reaches the endpoint in its own way:
| Language | What the program uses |
|---|---|
| JavaScript | lumo.api.create(AdminUsersApi) on LumoAuthBackend. It needs the package @lumoauth/api-client. |
| Python | AdminUsersApi(lumo.api). It needs the package lumoauth-api-client, which pip install "lumoauth[api]" installs. |
| PHP | $lumo->http()->request(...) with $lumo->http()->orgPath(...). The answer is an array. |
| Java | lumo.request(method, path, body, type) with lumo.orgPath(...). The answer becomes your own record type. |
| C# | lumo.RequestAsync<T>(method, path) with lumo.OrgPath(...). The answer becomes your own record type. |
In every language the call sends the API key, and an error status becomes one of the typed errors of the SDK.
Before you start
- An API key with the scope
admin:users:read. Create it in the portal under Applications & developer tools, API keys. - Three users to list. The setup script creates them. Its API key also needs
admin:users:write.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | An API key with the scope admin:users:read. The setup script also needs admin:users:write. |
SEARCH | Optional. The text that the email address, the name or the username of a user contains. Default: @contractors.example.com. |
The setup script creates three test users at contractors.example.com, so that the list has two pages. You can run it again at any time.
node operations/any-endpoint/setup.mjs
setup.mjs
// Creates three test users with addresses at contractors.example.com, so that
// the list of the recipe has more than one page. Run it again at any time.
//
// node operations/any-endpoint/setup.mjs
//
// The API key needs the scope admin:users:write.
import { randomBytes } from 'node:crypto';
import { ensure, printEnv } from '../../_lib/admin.mjs';
for (const [email, name] of [
['ana.ortiz@contractors.example.com', 'Ana Ortiz'],
['ben.okafor@contractors.example.com', 'Ben Okafor'],
['chloe.park@contractors.example.com', 'Chloe Park'],
]) {
await ensure('/admin/users', (u) => u.email === email, {
email,
name,
// The recipe never signs in as these users, so nobody needs the password.
password: `${randomBytes(18).toString('base64url')}#Aa1`,
emailVerified: true,
});
}
console.log('Three users at contractors.example.com are ready.');
printEnv({ SEARCH: '@contractors.example.com' });
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. JavaScript and Python use the generated client through the SDK. PHP, Java and C# use the request method of the SDK.
- Node.js
- Python
- PHP
- Java
- C#
// List users page by page with the generated client, which the SDK sets up
// with your credentials. The hand-written SDK has no call for this list.
//
// node operations/any-endpoint/js/list-users.mjs
//
// lumo.api needs the package @lumoauth/api-client next to @lumoauth/backend.
import { LumoAuthBackend } from '@lumoauth/backend';
const lumo = new LumoAuthBackend({
baseUrl: process.env.LUMOAUTH_URL,
orgId: process.env.LUMOAUTH_ORG_ID,
secretKey: process.env.LUMOAUTH_API_KEY,
});
// One class for each group of endpoints, with the base URL and the API key
// already set.
const { AdminUsersApi, ListUsersSortBy, ListUsersSortDir } = lumo.api.module;
const users = lumo.api.create(AdminUsersApi);
const search = process.env.SEARCH ?? '@contractors.example.com';
let total = 0;
for (let page = 1; ; page++) {
// In TypeScript the parameters have the type AdminUsersApiListUsersRequest,
// and the answer has the type ListUsersResponse. The answer is an axios
// response: the JSON is in its data field.
const { data: answer } = await users.listUsers({
orgId: process.env.LUMOAUTH_ORG_ID,
search,
sortBy: ListUsersSortBy.EMAIL,
sortDir: ListUsersSortDir.ASC,
page,
limit: 2,
});
console.log(`page ${page} of ${answer.pagination.totalPages}`);
for (const user of answer.data) console.log(` ${user.email} (${user.name})`);
total += answer.data.length;
if (!answer.pagination.hasNextPage) break;
}
console.log(`${total} users`);
node operations/any-endpoint/js/list-users.mjs
"""List users page by page with the generated client, which the SDK sets up
with your credentials. The hand-written SDK has no call for this list.
python operations/any-endpoint/python/list_users.py
client.api needs the package lumoauth-api-client: pip install "lumoauth[api]".
"""
import os
from lumoauth import LumoAuth
from lumoauth_api_client import AdminUsersApi
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
lumo = LumoAuth()
# One class for each group of endpoints. lumo.api is the generated ApiClient,
# with the base URL and the API key already set.
users = AdminUsersApi(lumo.api)
search = os.environ.get("SEARCH", "@contractors.example.com")
total = 0
page = 1
while True:
# The answer is a ListUsersResponse model, with typed fields.
answer = users.list_users(
org_id=os.environ["LUMOAUTH_ORG_ID"],
search=search,
sort_by="email",
sort_dir="ASC",
page=page,
limit=2,
)
print(f"page {page} of {answer.pagination.total_pages}")
for user in answer.data:
print(f" {user.email} ({user.name})")
total += len(answer.data)
if not answer.pagination.has_next_page:
break
page += 1
print(f"{total} users")
python operations/any-endpoint/python/list_users.py
<?php
// List users page by page with the transport of the SDK, which sends your
// credentials. The SDK has no method of its own for this list.
//
// php operations/any-endpoint/php/list-users.php
require __DIR__ . '/../../../php/vendor/autoload.php';
use LumoAuth\LumoAuth;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
$lumo = new LumoAuth();
// http() sends a request to any endpoint, with the API key, and turns an
// error status into the typed errors of the SDK. orgPath() adds the
// /orgs/{orgId}/api/v1 part of the path.
$http = $lumo->http();
$search = getenv('SEARCH') ?: '@contractors.example.com';
$total = 0;
for ($page = 1; ; $page++) {
// The answer is the decoded JSON, as an array.
$answer = $http->request('GET', $http->orgPath('/admin/users'), query: [
'search' => $search,
'sortBy' => 'email',
'sortDir' => 'ASC',
'page' => $page,
'limit' => 2,
]);
printf("page %d of %d\n", $page, $answer['pagination']['totalPages']);
foreach ($answer['data'] as $user) {
printf(" %s (%s)\n", $user['email'], $user['name']);
}
$total += count($answer['data']);
if (!$answer['pagination']['hasNextPage']) {
break;
}
}
printf("%d users\n", $total);
php operations/any-endpoint/php/list-users.php
// List users page by page with the request method of the SDK, which sends
// your credentials. The SDK has no method of its own for this list.
//
// java -cp "java/lib/*" operations/any-endpoint/java/ListUsers.java
import io.lumoauth.LumoAuth;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class ListUsers {
// The parts of the answer that the program reads. The SDK leaves out the
// fields that a record does not name.
record User(String email, String name) {}
record Pagination(int totalPages, boolean hasNextPage) {}
record UsersPage(List<User> data, Pagination pagination) {}
public static void main(String[] args) {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
LumoAuth lumo = LumoAuth.fromEnvironment();
String search = System.getenv().getOrDefault("SEARCH", "@contractors.example.com");
int total = 0;
for (int page = 1; ; page++) {
// orgPath() adds the /orgs/{orgId}/api/v1 part of the path. An
// error status becomes one of the typed exceptions of the SDK.
String path = lumo.orgPath("/admin/users")
+ "?search=" + URLEncoder.encode(search, StandardCharsets.UTF_8)
+ "&sortBy=email&sortDir=ASC&page=" + page + "&limit=2";
UsersPage answer = lumo.request("GET", path, null, UsersPage.class);
System.out.printf("page %d of %d%n", page, answer.pagination().totalPages());
for (User user : answer.data()) {
System.out.printf(" %s (%s)%n", user.email(), user.name());
}
total += answer.data().size();
if (!answer.pagination().hasNextPage()) {
break;
}
}
System.out.printf("%d users%n", total);
}
}
java -cp "java/lib/*" operations/any-endpoint/java/ListUsers.java
#:package LumoAuth@1.7.0
#:property PublishAot=false
// List users page by page with the request method of the SDK, which sends
// your credentials. The SDK has no method of its own for this list.
//
// dotnet run operations/any-endpoint/csharp/ListUsers.cs
using System.Text.Json.Serialization;
using LumoAuth;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
var lumo = LumoAuthClient.FromEnvironment();
var search = Environment.GetEnvironmentVariable("SEARCH") ?? "@contractors.example.com";
var total = 0;
for (var page = 1; ; page++)
{
// OrgPath() adds the /orgs/{orgId}/api/v1 part of the path. An error
// status becomes one of the typed exceptions of the SDK.
var path = lumo.OrgPath("/admin/users")
+ $"?search={Uri.EscapeDataString(search)}&sortBy=email&sortDir=ASC&page={page}&limit=2";
var answer = (await lumo.RequestAsync<UsersPage>("GET", path))!;
Console.WriteLine($"page {page} of {answer.Pagination.TotalPages}");
foreach (var user in answer.Data)
{
Console.WriteLine($" {user.Email} ({user.Name})");
}
total += answer.Data.Count;
if (!answer.Pagination.HasNextPage)
{
break;
}
}
Console.WriteLine($"{total} users");
// The parts of the answer that the program reads. The SDK matches the JSON
// names exactly, so each property names its field.
record User([property: JsonPropertyName("email")] string Email, [property: JsonPropertyName("name")] string? Name);
record Pagination([property: JsonPropertyName("totalPages")] int TotalPages, [property: JsonPropertyName("hasNextPage")] bool HasNextPage);
record UsersPage([property: JsonPropertyName("data")] List<User> Data, [property: JsonPropertyName("pagination")] Pagination Pagination);
dotnet run operations/any-endpoint/csharp/ListUsers.cs
Check the result
page 1 of 2
ana.ortiz@contractors.example.com (Ana Ortiz)
ben.okafor@contractors.example.com (Ben Okafor)
page 2 of 2
chloe.park@contractors.example.com (Chloe Park)
3 users
- The list has two pages because the program asks for two users on each page. Set
SEARCHto another text to list other users. - The portal shows each request of the key in the audit log, under Security, Audit logs. The entry is
api_key.used, and its actor is the name of the API key. - The Users reference lists every parameter of the list:
active,blocked,emailVerified,role,groupand others.
Limits
- In the generated clients, many calls that create or change something have no parameter for the request body. Examples are
createUser,updateUserandadminGroupsCreate. For such a call, use the request method of the SDK, or plain HTTP, and send the JSON body that the API reference describes. - A page holds at most 100 users.
- The search text is case-sensitive.