Custom REST routes

Custom REST routes in restdb.io lets you create new API endpoints with serverless Javascript functions.

You can create a route to serve any content, e.g. JSON, HTML, XML, etc. Custom routes are served under the /views/subroute of your database endpoint. E.g.

https://mydb-f1e0.restdb.io/views/myroute

or the same route under a custom secure domain.

https://example.com/myroute

Hello world Javascript as a custom GET /myroute:

// #!/javascript

const onGET = (req, res) => {
    res.end({"text": "Hello world!"});
}

Custom routes and APIs provides your data backend with more power and flexibility.

Custom REST routes are implemented as Pages. If you are familiar with this concept, you're good to go, otherwise check the docs here.

Creating custom REST routes

In developer mode, click the Pages/views + link. Enter the route and a description for the new page. Optionally add an icon.

new page

After saving the new Page, you can review the setting where you can see the full URL route and some other Page settings.

route settings

Clicking on the code editor in the left menu opens the code editor.

The first line is important to indicate that the code contains a custom route with Javascript. The canonical format for a custom route Javascript is:

// #!/javascript

// replace onXXX with onGET, onPOST, onPUT, onPATCH, onDELETE
const onXXX = (req, res) => {
    ...
}

The example below shows the mandatory Hello world! version for a custom route in restdb.io.

route javascript code

Clicking on the preview menu item, opens a new browser window and renders the output.

route preview

Securing your API

Accessing your custom route API without an API key will normally return an error code.

401 Unauthorized

You can protect your API with API keys just the same way as the other APIs in restdb.io.

Read the security docs here.

Opening you API for public routes

In some scenarios you want your API to be public avaliable. To serve a public route without an API key, open the Page settings and check the Allow public access to this view setting. The page URL will now change and you can share this URL. E.g.

https://www-routedemo-62f0.restdb.io/someroute

or with domain

https://example.com/someroute

Routing Javascript API

Custom REST routes are implemented as Javascript Codehooks. They share the same APIs and utility functions as any other Codehook.

For a custom route to respond to a REST verb, the corresponding method of the REST verb must be implemented as a Javascript function.

onGET(req, res)
onPOST(req, res)
onPUT(req, res)
onPATCH(req, res)
onDELETE(req, res)

Request

The request parameter has the following properties:

  • req.setting
    • Global database settings
  • req.body
    • JSON payload in POST, PUT PATCH and DELETE methods
  • req.params
    • URL parameters, e.g. ?col=red&type=2
  • req.pathparams
    • Path parameters, e.g. /someroute/:productID/:type
  • req.headers
    • HTTP headers
  • req.dbname
    • your database name

Response

The response parameter ends the request and sends back the output and header values from the code. You can send plain text or JSON objects.

res.end(
  {
      text: "<h1>Hello world!</h1>", 
      headers: {"content-type": "text/html"}
  }
)
res.end(
  {
    json: {
      "msg": "Hello world!",
      "count": 42 
    }
  }
)

Example

A custom route that runs a database query and manipulates the result.

// #!/javascript

/*
    Run route as a function
*/

const onGET = (req, res) => {
    db.get("/rest/company", {}, {$max: 10}, (dberr, dbdata) => {
        log.debug("Input", req);
        const json = dbdata.map( (el) => {
            return {name: el.name, letters: el.name.length}
            
        });
        json[0] = {"First record is special": "now! "+ new Date()};
        log.info("Got some data here", req, json);
            
        res.end({json: json});    
    })
}

Example JSON output:

[
    {
        "First record is special": "now! Sun Apr 15 2018 11:15:27 GMT-0400 (EDT)"
    },
    {
        "name": "Pfeffer Inc",
        "letters": 11
    },
    {
        "name": "Zboncak LLC",
        "letters": 11
    },
    {
        "name": "Bergstrom PLC",
        "letters": 13
    },
    {
        "name": "Bednar and Sons",
        "letters": 15
    },
    {
        "name": "VonRueden Inc",
        "letters": 13
    },
    {
        "name": "Beier LLC",
        "letters": 9
    },
    {
        "name": "Kreiger and Sons",
        "letters": 16
    },
    {
        "name": "Funk LLC",
        "letters": 8
    },
    {
        "name": "Friesen and Sons",
        "letters": 16
    }
]