Invoking APIs
SurrealDB allows you to define custom API endpoints that expose database operations through HTTP-style routes. The JavaScript SDK provides the .api() method to invoke these endpoints with full type safety, custom headers, and structured responses.
API References
| Method | Description |
|---|---|
db.api(prefix?) | Creates a SurrealApi instance for invoking user-defined endpoints |
api.get(path) | Invokes a GET endpoint |
api.post(path, body?) | Invokes a POST endpoint |
api.invoke(path, request?) | Invokes an endpoint with a custom request object |
Accessing API endpoints
To invoke user-defined endpoints, call .api() on any Surreal, SurrealSession, or SurrealTransaction instance. The returned SurrealApi object exposes HTTP-style methods like .get(), .post(), .put(), .delete(), and .patch().
By default, API calls return a response object containing body, status, and headers. Chaining .value() returns only the response body directly.
Defining type-safe APIs
You can define TypeScript types for your API paths to get compile-time type checking on both request bodies and responses. Each path maps HTTP methods to a tuple of [RequestBody, ResponseBody].
Setting request headers
You can set headers on individual requests by chaining .header(), or set default headers on the API instance using api.header(). Setting a header value to null removes it.
Using a path prefix
When working with a group of related endpoints, you can pass a prefix to .api(). All subsequent calls will be relative to that prefix.
Handling API errors
When an API call fails, the SDK throws an UnsuccessfulApiError. This error includes the path, HTTP method, and the full response object.
Learn more
SurrealApi API reference for the complete list of methods and type parameters
ApiPromise API reference for response configuration options
DEFINE API for defining custom API endpoints in SurrealQL