APIs
Any modern web application which needs to perform actions like retriving information or saving information use an API.
Previous.js allows you to create any kind of API with route handlers using the App Router.
Route Handlers
Route handlers are defined in a route.js
file inside the app/
directory:
If route.js
is defined in any directory the App Router will make this route publicly accessible.
return { GET: function(props) { return getJSON({ apiVersion: '1.0.0' }); } }
So in this example we can get access to the API using the URL acme.com/api
and the method GET returning an object in JSON format.
Good to know
Any standard HTTP methods are supported:
GET
,POST
,PUT
,PATCH
,DELETE
,HEAD
,OPTIONS
, etc.
Props
Unlike page routes, route handlers will only receive the following props:
PROP | TYPE | Description |
---|---|---|
params | object | URL params |
uri | string | Current URI |
data | object | Request Data |
Request Data
Use props.data
to access request data from URL query string or form payload data.
For example we can create this API endpoint with POST method:
return { POST: function(props) { return getJSON({ apiVersion: '1.0.0', test: props.data.test }); } }
Later we can use this API with a jQuery AJAX using POST method:
... $.post('/api/post', {test: 'Hello World!'}, function(data) { console.log(data); }); ...
Good to know
POST parameters will override GET parameters if using the same name.
Dynamic Requests
Route handlers also can use Dynamic Route Segments so we can create a route.js
file into app/api/blog/[id]/
folder to retrive dynamic data.
return { GET: function(props) { return getJSON({ id: props.params.id }); } }
Learn more about Dynamic Routes.
Handling Response
When using route handlers we can use the function getJSON
to ease process the response in JSON format with the corresponding content-type: application/json
HTTP HEADER.
This method is provided by Previous.js in server side. See more in Require section.
If you want to generate a response in other formats you must return an object with the following attributes:
Property | Type | Description |
---|---|---|
type | String | The content-type for the returning data. |
data | String | The returning data in its respective format. |
For example:
return { GET: function(props) { return { type: "text/csv", data: "Name,Qty\nOranges,10\nBananas,3\nApples,4" }; } }
Good to know
We have not tested binary formats on returning data, so we do not know if it works.
Redirections
Using the router we can setup a redirection for your API.
For example, we can redirect any request from the url /api/articles
to another API like:
return { GET: function(props) { return { redirect: "/api/news" }; } }