Creating routes
Sensai uses a file-system based router where the combination of a folder and a route
file define an API. A folder represents
a segment of your API URL while a route
file is used to expose an API.
Here's an example in how to create a /hello
API:
> api
> hello
+ route.ts <-- /hello
> user
+ index.ts
In the example above, the URL /user
is not an API as the folder user
does not contain
a route
file.
Using route
as an API identifier allow to colocate API endpoints with their
more complicated logic.
Nested routes
Folders inside each others allow to represent nested routes.
For example, to create the API /hello/world
, you can simply nest the 2 folders (hello
> world
) in the api
directory:
> api
> hello
> world
+ route.ts <-- /hello/world
Defining route handler
A route
is a special convention file exposing a default
function (a.k.a the route handler) for a given API URL. The handler will be executed whenever the API is called.
export default () => {
return "hello world";
};
Sensai abstract all the complexity of having to deal with API requests and API responses. You just need to export a JavaScript function with data that comes in and data that comes out, the rest is taken care of.
And that's not all! Sensai automatically generate documentation, add layers of security and more. As a developer, you just need to know how to write a function and you are good to go!
Route methods
Sensai supports HTTP defined methods (such as GET, POST, PUT just to name a few) with custom route extension. Here's an example:
> api
> hello
+ route.post.ts
The handler defined in route.post.ts
file above will only be executed on POST
requests made to /hello
.
Multiple route methods can be defined under a given API segment:
> api
> hello
+ route.ts
+ route.post.ts
+ route.get.ts
In the example above, GET
requests msde to /hello
will execute the route.get.ts
handler and POST
requests execute the route.post.ts
handler.
Any request methods other than GET
and POST
will execute the handler defined in the route.ts
file.
Please note route.ts
is equivalent to route.any.ts
where ANY
represents any HTTP method that is supplied at run time.
Sensai supports any extension to the HTTP protocol (such as WebDav) that define their own set of custom methods.