# Define endpoints (https://effetch.monarcode.dev/docs/endpoints/defining)

You define an endpoint once, and every call to it uses what you saved. This
page shows how to write a definition with `Fetch.endpoint`, what it can
hold, how its defaults combine with the client's and the call's, and what
you can read back from it.

## Define an endpoint

`Fetch.endpoint` takes a route, which is the method and the path in one
string, and what every call to it shares. It needs no client, so you can
define endpoints next to their schemas:

```ts
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";

const User = Schema.Struct({ id: Schema.Finite, name: Schema.String });
const NewUser = Schema.Struct({ name: Schema.String });

export const getUser = Fetch.endpoint("GET /users/:id", { output: User });
export const listUsers = Fetch.endpoint("GET /users", {
  output: Schema.Array(User),
});
export const createUser = Fetch.endpoint("POST /users", {
  input: NewUser,
  output: User,
});

getUser.route; // "GET /users/:id"
getUser.output; // User
getUser.error; // undefined, so the client's defaultError applies
```

A definition is plain data. It holds the route, the schemas and the
defaults, but it can't make a call until you bind it to a client. To bind
it, see [Share endpoints as a service](https://effetch.monarcode.dev/docs/endpoints/services).

## What a definition holds

Everything in a definition is optional. It takes the following options:

| Option         | What it does                                                                                                            |
| -------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `output`       | Decodes a 2xx body. Without it, a call succeeds with the raw `HttpClientResponse`.                                      |
| `error`        | Decodes an error body into `HttpError.body`, in place of the client's `defaultError`.                                   |
| `statusErrors` | Turns error responses into your own errors, by status. See [Errors by status](https://effetch.monarcode.dev/docs/errors/status-errors).              |
| `input`        | Encodes `body`, and makes `body` required on every call. `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints can't take one. |
| `headers`      | Headers sent with every call.                                                                                           |
| `responseMode` | What every call succeeds with. See [Read the response](https://effetch.monarcode.dev/docs/calls/responses).                                          |
| `query`        | A schema that types and encodes each call's query. See [Typed query parameters](https://effetch.monarcode.dev/docs/endpoints/typed-query).           |
| `stream`       | `"sse"` or `"ndjson"`, so every call returns a `Stream`. See [Streaming responses](https://effetch.monarcode.dev/docs/streaming).                    |

A `Fetch.endpoint` definition takes no `plugins`, because plugin overrides
are checked against a client's plugins, and a definition has no client yet.
You give them when you bind it, or in the definition of `api.endpoint`,
which defines and binds in one step (see
[Call an endpoint](https://effetch.monarcode.dev/docs/endpoints/calling)).

## Write the route

The route is an uppercase method, one space, then a path that starts with
`/` or a full `http://` or `https://` URL. TypeScript checks it as you type:
`"GTE /users"` and `"get /users"` don't compile, and your editor suggests
the methods.

`Fetch.endpoint` also checks the definition when it runs, and throws on
what can't work. A bad definition then fails as soon as its module is
imported, not on its first call. It throws on:

- a malformed route, which TypeScript only lets through after a cast;
- a `query` schema with a field that can't be encoded to a string, such as
  `Schema.instanceOf(Uint8Array)`;
- a `stream` that isn't `"sse"` or `"ndjson"`, or that comes with a
  `responseMode` or a `Fetch.bytes()` output.

## How defaults combine

An endpoint holds defaults, the client holds others, and each call can add
its own. They combine as follows:

- **Headers.** A call's headers win over the endpoint's, which win over the
  client's. A bound endpoint's headers are the ones given when binding, over
  the definition's. Unlike the client's, an endpoint's headers can set
  `content-type`, such as `application/merge-patch+json` for a `PATCH`,
  since one endpoint sends the same kind of body on every call.
- **Plugin overrides.** An override turns a plugin off for the endpoint, or
  changes its options, as in `{ bearer: false }` for a login that sends no
  token (see [Built-in plugins](https://effetch.monarcode.dev/docs/plugins)). The endpoint's overrides
  come from binding, or from `api.endpoint`'s definition. A call's override
  for the same plugin wins, and when both give options, they're merged. So
  an endpoint bound with `retry: false` can still be retried in one call
  with `plugins: { retry: { times: 2 } }`.
- **Schemas.** `output`, `input` and `query` belong to the endpoint, and a
  call can't change them.
- **Error body.** The endpoint's `error` schema replaces the client's
  `defaultError`. Without one, the endpoint uses the `defaultError` of the
  client it's bound to.
- **Errors by status.** The endpoint's `statusErrors` are tried first, then
  the client's. A call to an endpoint can't add a map of its own.
- **Response mode.** A call's `responseMode` wins over the endpoint's.
  A stream endpoint's calls can't take one.

## Read an endpoint's properties

An endpoint carries what it was defined with, so other code can read it.
`route`, `method` and `path` are there for log labels and cache keys, and
plugins get the same route, as `ctx.route` (see
[Write a plugin](https://effetch.monarcode.dev/docs/plugins/writing)). The schemas are there for things
such as decoding cached data or building test fixtures.

A definition from `Fetch.endpoint` and a bound endpoint have mostly the same
properties. A few differ, because only a bound endpoint has a client to
fall back on:

| Property       | On a definition                                | On a bound endpoint                                                                             |
| -------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `route`        | The route, such as `"GET /users/:id"`          | The same                                                                                        |
| `method`       | The method, such as `"GET"`                    | The same                                                                                        |
| `path`         | The path, such as `"/users/:id"`               | The same                                                                                        |
| `output`       | The schema, or `undefined` without one         | The same                                                                                        |
| `input`        | The schema, or `undefined` without one         | The same                                                                                        |
| `error`        | The schema, or `undefined` without one         | The endpoint's schema, else the client's `defaultError`, else `Schema.Unknown`                  |
| `statusErrors` | The map as given, or `undefined` without one   | For each status, a list of the endpoint's schemas, then the client's. `{}` when neither has any |
| `headers`      | The headers, or `undefined` without any        | Not there                                                                                       |
| `responseMode` | The mode, or `undefined` without one           | The same                                                                                        |
| `query`        | The schema, or `undefined` without one         | The same                                                                                        |
| `stream`       | `"sse"`, `"ndjson"`, or `undefined`            | The same                                                                                        |
| `url(options)` | The URL a call would go to, without a base URL | The same, starting with the client's `baseUrl`                                                  |

For `url`, see [Build an endpoint's URL](https://effetch.monarcode.dev/docs/endpoints/urls).

## What's next

- [Share endpoints as a service](https://effetch.monarcode.dev/docs/endpoints/services): bind your
  definitions to a client and share them as a service.
- [Call an endpoint](https://effetch.monarcode.dev/docs/endpoints/calling): see what goes in each call,
  and other ways to bind.
- [Typed query parameters](https://effetch.monarcode.dev/docs/endpoints/typed-query): give an endpoint a
  schema for its query.