docs/docs/en/integration/api-keys/usage.md
This guide demonstrates how to use API Keys in NocoBase to retrieve data through a practical "To-Dos" example. Follow the step-by-step instructions below to understand the complete workflow.
An API Key is a secure token that authenticates API requests from authorized users. It functions as a credential that validates the identity of the requester when accessing the NocoBase system via web applications, mobile apps, or backend scripts.
In the HTTP request header, you'll see a format like:
Authorization: Bearer {API key}
The "Bearer" prefix indicates that the following string is an authenticated API Key used to verify the requester's permissions.
API Keys are typically used in the following scenarios:
API Keys provide multiple security benefits: identity verification, usage monitoring, request rate limiting, and threat prevention, ensuring the stable and secure operation of NocoBase.
Ensure that the built-in Auth: API Keys plugin is activated. Once enabled, a new API Keys configuration page will appear in the system settings.
For demonstration purposes, create a collection named todos with the following fields:
idtitlecompletedAdd some sample records to the collection:
API Keys are bound to user roles, and the system determines request permissions based on the assigned role. Before creating an API Key, you must create a role and configure the appropriate permissions. Create a role named "To Dos API Role" and grant it full access to the todos collection.
If the "To Dos API Role" is not available when creating an API Key, ensure that the current user has been assigned this role:
After role assignment, refresh the page and navigate to the API Keys management page. Click "Add API Key" to verify that the "To Dos API Role" appears in the role selection.
For better access control, consider creating a dedicated user account (e.g., "To Dos API User") specifically for API Key management and testing. Assign the "To Dos API Role" to this user.
After submitting the form, the system will display a confirmation message with the newly generated API Key. Important: Copy and securely store this key immediately, as it will not be displayed again for security reasons.
Example API Key:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInJvbGVOYW1lIjoidG9kb3MiLCJpYXQiOjE3NDA5OTY1ODAsImV4cCI6MzMyOTg1OTY1ODB9.tXF2FCAzFNgZFPXqSBbWAfEvWkQwz0-mtKnmOTZT-5M
APP_KEY environment variable. Do not modify this variable, as doing so will invalidate all existing API Keys in the system.Open the API Documentation plugin to view the request methods, URLs, parameters, and headers for each API endpoint.
NocoBase provides standard CRUD (Create, Read, Update, Delete) APIs for data manipulation:
List Query (list API):
GET {baseURL}/{collectionName}:list
Request Header:
- Authorization: Bearer <API key>
Create Record (create API):
POST {baseURL}/{collectionName}:create
Request Header:
- Authorization: Bearer <API key>
Request Body (in JSON format), for example:
{
"title": "123"
}
Update Record (update API):
POST {baseURL}/{collectionName}:update?filterByTk={id}
Request Header:
- Authorization: Bearer <API key>
Request Body (in JSON format), for example:
{
"title": "123",
"completed": true
}
Delete Record (delete API):
POST {baseURL}/{collectionName}:destroy?filterByTk={id}
Request Header:
- Authorization: Bearer <API key>
Where:
{baseURL}: Your NocoBase system URL{collectionName}: The collection nameExample: For a local instance at localhost:13000 with a collection named todos:
http://localhost:13000/api/todos:list
Create a GET request in Postman with the following configuration:
http://localhost:13000/api/todos:list)Authorization header with the value:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInJvbGVOYW1lIjoidG9kb3MiLCJpYXQiOjE3NDA5OTY1ODAsImV4cCI6MzMyOTg1OTY1ODB9.tXF2FCAzFNgZFPXqSBbWAfEvWkQwz0-mtKnmOTZT-5M
Successful Response:
{
"data": [
{
"createdAt": "2025-03-03T09:57:36.728Z",
"updatedAt": "2025-03-03T09:57:36.728Z",
"completed": null,
"createdById": 1,
"id": 1,
"title": "eat food",
"updatedById": 1
}
],
"meta": {
"count": 1,
"page": 1,
"pageSize": 20,
"totalPage": 1
}
}
Error Response (Invalid/Expired API Key):
{
"errors": [
{
"message": "Your session has expired. Please sign in again.",
"code": "INVALID_TOKEN"
}
]
}
Troubleshooting: Verify role permissions, API Key binding, and token format if authentication fails.
Postman allows you to export the request in various formats. Example cURL command:
curl --location 'http://localhost:13000/api/todos:list' \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInJvbGVOYW1lIjoidG9kb3MiLCJpYXQiOjE3NDA5OTY1ODAsImV4cCI6MzMyOTg1OTY1ODB9.tXF2FCAzFNgZFPXqSBbWAfEvWkQwz0-mtKnmOTZT-5M'
NocoBase 2.0 supports writing native JavaScript code directly in pages using JS blocks. This example demonstrates how to fetch external API data using API Keys.
In your NocoBase page, add a JS block and use the following code to fetch to-do list data:
// Fetch to-do list data using API Key
async function fetchTodos() {
try {
// Show loading message
ctx.message.loading('Fetching data...');
// Load axios library for HTTP requests
const axios = await ctx.requireAsync('https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js');
if (!axios) {
ctx.message.error('Failed to load HTTP library');
return;
}
// API Key (replace with your actual API key)
const apiKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInJvbGVOYW1lIjoidG9kb3MiLCJpYXQiOjE3NDA5OTY1ODAsImV4cCI6MzMyOTg1OTY1ODB9.tXF2FCAzFNgZFPXqSBbWAfEvWkQwz0-mtKnmOTZT-5M';
// Make API request
const response = await axios.get('http://localhost:13000/api/todos:list', {
headers: {
'Authorization': `Bearer ${apiKey}`
}
});
// Display results
console.log('To-Do List:', response.data);
ctx.message.success(`Successfully fetched ${response.data.data.length} items`);
// You can process the data here
// For example: display in a table, update form fields, etc.
} catch (error) {
console.error('Error fetching data:', error);
ctx.message.error('Failed to fetch data: ' + error.message);
}
}
// Execute the function
fetchTodos();
Authorization header with Bearer prefixThis guide covered the complete workflow for using API Keys in NocoBase:
Additional Resources: