A Haskell's Servant inspired library for defining type-safe REST APIs using Typescript.
Right now, it only supports express but it can support other server setups.
Obviously Servant, but also Rest.ts and RESTyped.
npm i -S servant-ts fp-ts io-ts
First, you need to define your API, optionally using the awesome library io-ts.
import * as t from "io-ts";
import { GET, capture, asJson } from "servant-ts/dist/io-ts";
const User = t.strict({
id: t.Int,
username: t.string,
email: t.string
});
/*
* GET /user/:id
* where :id must be an integer
*
* Response example:
* Status: 200
* Contet-Type: application/json
* Body:
* {
* "id": 1,
* "username": "johndoe",
* "email": "[email protected]"
* }
*/
const api = {
userById: GET`/user/${capture("id", t.Int)}`
.response(asJson(User))
};
Then, you need to implement tha API:
const app = express();
app.use(
"/api",
createApi(api, {
userById: async (request) => {
const { captures: { id } } = request;
// get the user, maybe from a database ...
return user;
}
})
);
A backend implementation of the Real World specification using this library and Postgres SQL.
- Make it solid
- Better error handling and specification
- Swagger specification generator
- Fastify support
- JSON schema generator
- Make io-ts optional