# REST Server Quickstart

*This page explains how to initialize the REST Server, register endpoints, and expose your own functions over HTTP.*

## Usage

To use the REST Server module:

1. Load the the `rest` module.
2. Initialize the framework, using the `.rest.init` function.
3. Register the endpoints, using the `.rest.register` function.
4. (Optional) On a request to `.z.ph` or `.z.pp`, forward execution to `.rest.process` to process the incoming request and return the result.

> **Note — Note**
>
> The examples below assume a `.rest` namespace.
>
> ```q
> .rest:use`kx.rest;
> ```
>
## Initialize the REST server framework

Before registering endpoints, we set a listening port and initialize the REST Server:
```q
/ The server will listen on port 8080
\p 8080

/ Initialize the framework with autoBind enabled
.rest.init enlist[`autoBind]!enlist[1b] / Initialize
```

Use the `.rest.init` function to initialize the framework. Call it without arguments (for example `.rest.init[]`) for minimal setup, or as a unary (with a dictionary argument) to perform further steps such as auto-binding to `.z.ph` and `.z.pp` (as in the above example).

With the `autoBind` option specified as `1b`, if no endpoint matches a request, the server delegates to the next handler (if applicable). Conversely if `autoBind` is not specified (or specified as `0b`), unmatched requests return an HTTP 404 code.

Note that when auto-binding is disabled, the application binds `.rest.process` to `.z.ph` and `.z.pp`, and performs any chaining as needed.

## Register the endpoints

Endpoints map HTTP methods and URL paths to q functions. First, we define the `.db.getAllCustomers` and `.db.getCustomersById` functions, so we can later map them to the endpoints:
```q
.db.getAllCustomers:{
  x[`arg;`cnt]#select from customers where i>=x[`arg;`i]};

.db.getCustomersById:{
  select from customers where id in x[`arg;`id]};
```

Here is an example with two endpoints:
```q
// Register endpoints
.rest.register[`get;
  "/customers";
  "Returns all customers";
  .db.getAllCustomers;
  .rest.reg.data[`i;-6h;0b;0;"Offset to first row"],
    .rest.reg.data[`cnt;-6h;0b;10;"Number of rows to return"] ]

.rest.register[`get;
  "/customers/{id}";
  "Returns one or more customers by their IDs";
  .db.getCustomersById;
  .rest.reg.data[`id;6h;1b;0;"One or more customer IDs"] ]
```

After we initialized the framework with `autoBind` set to `1b`, we created two endpoints, as follows:

`get /customers`

: This endpoint returns all customers. It expects two parameters: 

    - `i (integer)` is the offset of first row to return
    - `cnt (integer)` is the number of rows to return

: Both parameters are optional, and have default values of `0` and `10` respectively. The endpoint is mapped to the `.db.getAllCustomers` function defined earlier.

: To query the endpoint, run the following command:
    ```bash
    curl 'localhost:8080/customers'
    curl 'localhost:8080/customers?i=10&cnt=10'
    ```

`get /customers/{id}`

: This endpoint returns one or more customers based on their IDs. It expects one parameter: `id (integer[])`, which is an input parameter in the form of a **path variable**. The value of this parameter is determined at matching time. The endpoint is mapped to the `.db.getCustomersById` function defined earlier.


### How to register endpoints

Use the `.rest.register` function to register an endpoint. The registration contains the following components:

-   The operation and path of the endpoint
-   A description summarizing the purpose of the endpoint
-   The handler function
-   Optional definition of user input, which includes: path variables, query string, headers, and request body (for `post`/`put` based endpoints)
-   Optional definition of result object

The operation is arbitrary and refers to the action being performed, typically one of the standard HTTP methods defined by the REST architecture: 

- `GET`
- `POST`
- `PUT`
- `DELETE`

The path is the part of the URL that follows the host and port (for example, `/customers`). It identifies the resource targeted of the operation. Paths can be customized and may include variables that act as parameters to the endpoint. For example, `/db/{table}/schema` is a valid path that has a variable named `table`.

The handler function is responsible for performing the activity of the endpoint. It works as follows:

User input definitions specify the properties of the expected input parameters which include:

- path-variables and query-string (using `.rest.reg.data`)
- headers (using `.rest.reg.header`)
- JSON-based request body (using `.rest.reg.body`). 

For example, the request `/db/{x}/{y}/z?i=0&cnt=10` has the following input parameters: `x`, `y`, `i`, and `cnt`. You can specify the name, data type, necessity, default value, and description of each parameter. 

The framework uses this information to:

-   Ensure the required parameters are supplied in the request, failing the request if any is missing
-   Parse the value using the expected data type

The handler also has access to the raw user input, which is useful when some or all of the input values are unknown at the time of registration.

Output definition specifies the schema of the result (using `.rest.reg.output`). The framework doesn't currently use the definition, but it is good practice to specify it for future purposes.

## Request processing

An HTTP request contains the following components:

-   HTTP method
-   Path
-   Query string
-   HTTP headers
-   Request body (applies to `POST`, `PUT`, and `DELETE`)

The HTTP method generally specifies the REST operation; in KDB-X, it is limited to `GET` and `POST`. Thus, the framework looks for the operation in the `http-method` HTTP header, and if not present defaults to `GET` (for `.z.ph`), or `POST` (for `.z.pp`).  It is thus important to use a front-end API gateway (like the AWS HTTP API gateway) that can populate `http-method` HTTP header, and convert `PUT`, and `DELETE` HTTP methods to `POST`, leaving `GET` requests as they are. Refer to the [request handling](https://code.kx.com/q/kb/http/#request-handling) for details.

When a request is received, both `operation` and `path` are combined to find a matching endpoint, favoring exact matches over ones containing variables (for example, `/a/b/c` vs `/a/{x}/c`).

User input is then processed, distinguishing between the following categories:

- User input specified using the `.rest.reg.data` function. These contain path variables (like `id` in `/customers/{id}`) and query-string parameters. Values are parsed according to their datatype. If a parameter is missing from the request, then its default value is used. But if the missing parameter is marked required, then the request fails with 400 HTTP status code (with the names of the missing required parameters included in the response). Values of input parameters are passed to the handler function as dictionary under `arg` key. Note that raw input parameters (as they appear in the request) are also passed to the handler function under the `rawArg` key.

- Request body (where applicable) is expected to be in JSON format. It is deserialized into a KDB-X data structure using `.j.k`, and  passed to the handler function under `data` key.

- Request body (in case of `post` or `put` operation) is expected to be in JSON format. If the endpoint has body input specified using the `.rest.reg.body` function, then the elements of the defined object are parsed from the input (including nested objects) according to their datatypes and necessity settings. Similar to input parameters, the raw body is passed to the handler under `rawData` key.

- HTTP headers are passed untouched to the handler function under `hdr` key.

After input is collected, the handler function is invoked. If the function is declared to take arguments with the same names as the endpoint parameters (or `body` if endpoint is comprised only of a `body` parameter), then the function is variadically invoked with its arguments mapped from the request input. Otherwise, the function is invoked as a unary with a dictionary containing the following keys:

-   REST operation of the endpoint
-   The path of the endpoint
-   Values of processed input parameters
-   Raw input parameters present in the request
-   Value of processed body object, which is typically a dictionary if the body is of an object type, but can be of any type as specified by `reg.body` function.
-   Raw KDB-X form of the request body (if present)
-   HTTP headers

The handler function is expected to return its response in one of the following forms:

- A KDB-X data structure (typically a dictionary or a table), which is serialized to JSON by the framework before being returned to the client
- Result of the `.rest.util.response` function, which gives the handler control over the HTTP status code, and content type of the response (available post release 1.0.0)
- Result of the `.rest.util.httpResponse` function, which gives the handler total control over the response
- If there is a problem with input, the handler must call `.util.throw` to signal an error

## Next steps

- Refer to the [REST server examples](examples.md) for a deeper understanding of the REST server and RESTful APIs.
- Check the [REST Server Release Notes](./release-notes/changelog.md) for version history and fixes.
