Skip to content

Declare HTTP APIs with api

An api declaration lists the endpoints of an HTTP API: each one's method, path, inputs, success type and errors with their status codes. It compiles to an Effect HttpApi, so the same value gives you a typed server, a typed client and an OpenAPI document. Use it where you would build an HttpApi from HttpApiGroup and HttpApiEndpoint calls. VIP-78 defines the form.

import { OpenApi } from "effect/http-api"
 
export schema NoteId = brand string
 
export schema Note {
  readonly id: NoteId
  readonly title: string
}
 
export schema error NoteNotFound {
  readonly id: NoteId
}
 
export api NotesApi {
  base "/api"
 
  GET    "/notes"     as list   (query: { q?: string; limit?: int }) -> ReadonlyArray<Note>
  GET    "/notes/:id" as get    (path: { id: NoteId })               -> Note ! NoteNotFound @ 404
  PUT    "/notes/:id" as save   (path: { id: NoteId }, body: Note)   -> Note ! NoteNotFound @ 404
  DELETE "/notes/:id" as remove (path: { id: NoteId })               -> void @ 204 ! NoteNotFound @ 404
 
  group health {
    GET "/health" -> { readonly ok: boolean }
  }
}
// Run in an effect function: try Console.log(Object.keys(OpenApi.fromApi(NotesApi).paths).sort())
[ '/api/health', '/api/notes', '/api/notes/{id}' ]

NotesApi is an ordinary Effect HttpApi value. Pass it to HttpApiBuilder.group(NotesApi, "NotesApi", …) to implement the endpoints, to HttpApiClient.make(NotesApi, …) for a client, or to OpenApi.fromApi(NotesApi) for the OpenAPI document.

An endpoint

An endpoint is METHOD "path" as name (sections) -> Success ! Error @ status:

PartMeans
GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONSThe HTTP method
"/notes/:id"The path; :id is a path parameter
as getThe endpoint's name; without it the compiler derives one, such as getHealth for GET "/health"
(path: …, query: …, headers: …, body: …)The inputs, each a schema or an inline record of schema fields
-> NoteThe success type; @ 204 sets its status
! NoteNotFound @ 404An error schema and its status; join several with |

base "/api" prefixes every path. Endpoints written at the top belong to a group named after the API, here "NotesApi"; group health { … } makes a named group. Outside a declaration start, api is an ordinary identifier, so const api = client still works.

Rules

Every type in an endpoint must have a schema, because the server decodes and encodes it. A name that is only a TypeScript type, such as an interface, is EK7806.

MistakeCode
A path, query, headers, body, success or error type that is not a schemaEK7806

The compiler also rejects a malformed path, path keys that differ from the path's parameters, two endpoints with one name or route, a body on a GET or HEAD, a status outside 100 to 599, and a declare api.

// expect-error: EK7806
interface Todo { readonly title: string }
 
export api TodosApi {
  GET "/todos" as list -> ReadonlyArray<Todo>
}