# Encore Api

> Define typed API endpoints in Encore.ts using `api(...)` from `encore.dev/api`. Covers typed request/response interfaces, path/query/header/cookie params, request validation, and `APIError`. For raw endpoints (`api.raw()`) and inbound webhooks, use `encore-webhook` instead.

- **Type:** Skill
- **Install:** `agentstack add skill-encoredev-skills-api`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [encoredev](https://agentstack.voostack.com/s/encoredev)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** Apache-2.0
- **Upstream author:** [encoredev](https://github.com/encoredev)
- **Source:** https://github.com/encoredev/skills/tree/main/encore/api
- **Website:** https://encore.dev

## Install

```sh
agentstack add skill-encoredev-skills-api
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Encore API Endpoints

## Instructions

When creating API endpoints with Encore.ts, follow these patterns:

### 1. Import the API module

```typescript
import { api } from "encore.dev/api";
```

### 2. Define typed request/response interfaces

Always define explicit TypeScript interfaces for request and response types:

```typescript
interface CreateUserRequest {
  email: string;
  name: string;
}

interface CreateUserResponse {
  id: string;
  email: string;
  name: string;
}
```

### 3. Create the endpoint

```typescript
export const createUser = api(
  { method: "POST", path: "/users", expose: true },
  async (req: CreateUserRequest): Promise => {
    // Implementation
  }
);
```

## API Options

| Option | Type | Description |
|--------|------|-------------|
| `method` | string | HTTP method: GET, POST, PUT, PATCH, DELETE |
| `path` | string | URL path, supports `:param` and `*wildcard` |
| `expose` | boolean | If true, accessible from outside (default: false) |
| `auth` | boolean | If true, requires authentication |
| `sensitive` | boolean | If true, redacts request/response payloads from traces |

## Request/Response Patterns

Encore supports four endpoint configurations:

```typescript
// Both request and response
export const createUser = api(
  { method: "POST", path: "/users", expose: true },
  async (req: CreateRequest): Promise => { ... }
);

// Response only (no request body)
export const listUsers = api(
  { method: "GET", path: "/users", expose: true },
  async (): Promise => { ... }
);

// Request only (no response body)
export const deleteUser = api(
  { method: "DELETE", path: "/users/:id", expose: true },
  async (req: DeleteRequest): Promise => { ... }
);

// Neither request nor response
export const ping = api(
  { method: "GET", path: "/ping", expose: true },
  async (): Promise => { ... }
);
```

## Custom HTTP Status Codes

Include an `HttpStatus` field in your response to return custom status codes:

```typescript
import { api, HttpStatus } from "encore.dev/api";

interface CreateResponse {
  id: string;
  status: HttpStatus;
}

export const create = api(
  { method: "POST", path: "/items", expose: true },
  async (req: CreateRequest): Promise => {
    const item = await createItem(req);
    return { id: item.id, status: HttpStatus.Created };  // Returns 201
  }
);
```

## Parameter Types

### Path Parameters

```typescript
// Path: "/users/:id"
interface GetUserRequest {
  id: string;  // Automatically mapped from :id
}
```

### Query Parameters

```typescript
import { Query } from "encore.dev/api";

interface ListUsersRequest {
  limit?: Query;
  offset?: Query;
}
```

### Headers

```typescript
import { Header } from "encore.dev/api";

interface WebhookRequest {
  signature: Header;
  payload: string;
}
```

### Cookies

```typescript
import { Cookie } from "encore.dev/api";

interface SessionRequest {
  session?: Cookie;
  settings?: Cookie;
}
```

## Request Validation

Encore validates requests at runtime using TypeScript types. Add constraints for stricter validation:

```typescript
import { api } from "encore.dev/api";
import { Min, Max, MinLen, MaxLen, IsEmail, IsURL } from "encore.dev/validate";

interface CreateUserRequest {
  email: string & IsEmail;                    // Must be valid email
  username: string & MinLen & MaxLen;  // 3-20 characters
  age: number & Min & Max;           // Between 13 and 120
  website?: string & IsURL;                   // Optional, must be URL if provided
}
```

### Combining Validation Rules

Use `&` for AND logic (must pass all rules) and `|` for OR logic (must pass at least one):

```typescript
import { IsEmail, IsURL, MinLen, MaxLen } from "encore.dev/validate";

interface ContactRequest {
  // Must be valid email OR valid URL
  contact: string & (IsEmail | IsURL);
  // Must be 5-100 chars AND be a valid URL
  website: string & MinLen & MaxLen & IsURL;
}
```

### Available Validators

| Validator | Applies To | Example |
|-----------|-----------|---------|
| `Min` | number | `age: number & Min` |
| `Max` | number | `count: number & Max` |
| `MinLen` | string, array | `name: string & MinLen` |
| `MaxLen` | string, array | `tags: string[] & MaxLen` |
| `IsEmail` | string | `email: string & IsEmail` |
| `IsURL` | string | `link: string & IsURL` |
| `StartsWith` | string | `id: string & StartsWith` |
| `EndsWith` | string | `file: string & EndsWith` |
| `MatchesRegexp` | string | `code: string & MatchesRegexp` |

### Validation Error Response

Invalid requests return 400 with details:

```json
{
  "code": "invalid_argument",
  "message": "validation failed",
  "details": { "field": "email", "error": "must be a valid email" }
}
```

## Error Handling

Use `APIError` for proper HTTP error responses:

```typescript
import { 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");
```

## Common Error Codes

| Code | HTTP Status | Usage |
|------|-------------|-------|
| `NotFound` | 404 | Resource doesn't exist |
| `InvalidArgument` | 400 | Bad input |
| `Unauthenticated` | 401 | Missing/invalid auth |
| `PermissionDenied` | 403 | Not allowed |
| `AlreadyExists` | 409 | Duplicate resource |

## Static Assets

Serve static files (HTML, CSS, JS, images) with `api.static`:

```typescript
import { 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" }
);
```

### Path Syntax

- `*path` - Standard wildcard: matches all paths under the prefix (e.g., `/static/*path`)
- `!path` - Fallback routing: serves static files at domain root without conflicting with other API endpoints. Use this for SPAs where unmatched routes should serve `index.html`

## Guidelines

- Always use `import` not `require`
- Define explicit interfaces for type safety
- Use `expose: true` only for public endpoints
- Throw `APIError` instead of returning error objects
- For inbound webhooks (Stripe, GitHub, etc.) use `api.raw` — see the `encore-webhook` skill
- Path parameters are automatically extracted from the path pattern
- Use validation constraints (`Min`, `MaxLen`, etc.) for user input

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [encoredev](https://github.com/encoredev)
- **Source:** [encoredev/skills](https://github.com/encoredev/skills)
- **License:** Apache-2.0
- **Homepage:** https://encore.dev

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-encoredev-skills-api
- Seller: https://agentstack.voostack.com/s/encoredev
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
