Loading...
Loading...
Create type-safe API endpoints with Encore.ts.
npx skill4agent add encoredev/skills encore-apiimport { api } from "encore.dev/api";interface CreateUserRequest {
email: string;
name: string;
}
interface CreateUserResponse {
id: string;
email: string;
name: string;
}export const createUser = api(
{ method: "POST", path: "/users", expose: true },
async (req: CreateUserRequest): Promise<CreateUserResponse> => {
// Implementation
}
);| Option | Type | Description |
|---|---|---|
| string | HTTP method: GET, POST, PUT, PATCH, DELETE |
| string | URL path, supports |
| boolean | If true, accessible from outside (default: false) |
| boolean | If true, requires authentication |
// Path: "/users/:id"
interface GetUserRequest {
id: string; // Automatically mapped from :id
}import { Query } from "encore.dev/api";
interface ListUsersRequest {
limit?: Query<number>;
offset?: Query<number>;
}import { Header } from "encore.dev/api";
interface WebhookRequest {
signature: Header<"X-Webhook-Signature">;
payload: string;
}import { api, Min, Max, MinLen, MaxLen, IsEmail, IsURL } from "encore.dev/api";
interface CreateUserRequest {
email: string & IsEmail; // Must be valid email
username: string & MinLen<3> & MaxLen<20>; // 3-20 characters
age: number & Min<13> & Max<120>; // Between 13 and 120
website?: string & IsURL; // Optional, must be URL if provided
}| Validator | Applies To | Example |
|---|---|---|
| number | |
| number | |
| string, array | |
| string, array | |
| string | |
| string | |
{
"code": "invalid_argument",
"message": "validation failed",
"details": { "field": "email", "error": "must be a valid email" }
}api.rawexport const stripeWebhook = api.raw(
{ expose: true, path: "/webhooks/stripe", method: "POST" },
async (req, res) => {
const sig = req.headers["stripe-signature"];
// Handle raw request...
res.writeHead(200);
res.end();
}
);APIErrorimport { APIError, ErrCode } from "encore.dev/api";
// Throw with error code
throw new APIError(ErrCode.NotFound, "user not found");
// Or use shorthand
throw APIError.notFound("user not found");
throw APIError.invalidArgument("email is required");
throw APIError.unauthenticated("invalid token");| Code | HTTP Status | Usage |
|---|---|---|
| 404 | Resource doesn't exist |
| 400 | Bad input |
| 401 | Missing/invalid auth |
| 403 | Not allowed |
| 409 | Duplicate resource |
api.staticimport { api } from "encore.dev/api";
// Serve files from ./assets under /static/*
export const assets = api.static(
{ expose: true, path: "/static/*path", dir: "./assets" }
);
// Serve at root (use !path for fallback routing)
export const frontend = api.static(
{ expose: true, path: "/!path", dir: "./dist" }
);
// Custom 404 page
export const app = api.static(
{ expose: true, path: "/!path", dir: "./public", notFound: "./404.html" }
);importrequireexpose: trueapi.rawapiAPIErrorMinMaxLen