The SurrealApi class exposes methods to interact with user-defined API endpoints in SurrealDB. It provides type-safe HTTP-style methods (GET, POST, PUT, DELETE, PATCH, TRACE) for invoking custom database APIs.
SurrealApi allows you to access custom API endpoints defined in your SurrealDB database. The class supports type-safe API definitions for better development experience.
// Define your API paths with types type MyPaths={ "/users":{get:[void,User[]]}; "/users/:id":{get:[void,User]}; "/users":{post:[CreateUserInput,User]}; };
// Access with type safety constapi=db.api<MyPaths>(); constusers=awaitapi.get("/users");// Type: User[]
// Type-safe API access constapi=db.api<MyPaths>();
// API with path prefix constusersApi=db.api<MyPaths>("/users");
Type Definitions
PathDef
Defines the HTTP methods available for an API path:
type PathDef=Partial<Record<HttpMethod,MethodDef>>; type HttpMethod="get"|"post"|"put"|"delete"|"patch"|"trace"; type MethodDef=[RequestBody,ResponseBody]|[];
Example Path Definitions
type MyApiPaths={ // GET endpoint with no request body, returns User[] "/users":{ get:[void,User[]]; post:[CreateUserRequest,User]; }; // Dynamic path parameters [K:`/users/${string}`]:{ get:[void,User]; put:[UpdateUserRequest,User]; delete:[void,void]; }; // POST endpoint with request/response bodies "/auth/login":{ post:[{email:string;password:string},{token:string}]; }; };
Methods
.header()
Configure a header for all requests sent by this API instance. Useful for setting common headers like authentication tokens or content types.
Method Syntax
api.header(name,value)
Parameters
Parameter
Type
Description
name
string
The name of the header to configure.
value
string | null
The value to set, or null to remove the header.
Returns
void
Examples
Set Custom Header
api.header('X-API-Key','my-secret-key');
Remove Header
api.header('X-API-Key',null);
Set Authorization Header
api.header('Authorization',`Bearer ${token}`);
.invoke()
Invoke a user-defined API with a custom request object. This is the generic method used by all HTTP method-specific functions.
Tip
Prefer using method-specific functions (.get(), .post(), etc.) for better type safety.
type UserPaths={ "/":{get:[void,User[]]}; [K:`/${string}`]:{ get:[void,User]; put:[UpdateUserRequest,User]; delete:[void,void]; }; };
// Create API with prefix constusersApi=db.api<UserPaths>("/users");
// Calls are prefixed automatically constallUsers=awaitusersApi.get("/");// GET /users/ constuser=awaitusersApi.get("/123");// GET /users/123 constupdated=awaitusersApi.put("/123",data);// PUT /users/123