03: basic routing

An intro to routes

03_basic_routing
Author

Kennedy Mwavu

Published

July 10, 2024

Run app

  1. cd into the 03_basic_routing/ dir:

    cd 03_basic_routing/
  2. Fire up R:

    R
  3. Restore package dependencies:

    renv::restore()

    Once done, exit R.

  4. index.R is the entry point. To start the app, run this on the terminal:

    Rscript index.R

Explanation

This app starts a server and listens on port 3000 for connections.

It has two endpoints:

  • /
  • /user

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Route definition takes the following structure:

app$METHOD(PATH, HANDLER)
  • app is an instance of ambiorix.
  • METHOD is an HTTP request method, in lowercase.
  • HANDLER is the function executed when the route is matched.

The following examples illustrate defining simple routes.

Respond with Hello World! on the homepage:

app$get("/", \(req, res) {
  res$send("Hello World!")
})

Respond to POST request on the root route (/), the application’s home page:

app$post("/", \(req, res) {
  res$send("Got a POST request")
})

Respond to a PUT request to the /user route:

app$put("/user", \(req, res) {
  res$send("Got a PUT request at /user")
})

Respond to a DELETE request to the /user route:

app$delete("/user", \(req, res) {
  res$send("Got a DELETE request at /user")
})

Keep this in mind:

  • Browsers issue a GET request by default. This means that once you run this example and visit localhost 3000, you’ll only be able to access the homepage (/).
  • The easiest way to see the responses from the other routes would be to either:
    • Install Postman and make the requests from there (Recommended). The free tier is more than enough. Here is how issuing the various requests above would look like: GET request to / POST request to / POST request to /user DELETE request to /user
    • Open another R session and use httr2 to make requests to the endpoints.

A simple JSON API

You’re now ready to build ✨a simple JSON API✨.