Run app
cd
into the03_basic_routing/
dir:cd 03_basic_routing/
Fire up R:
R
Restore package dependencies:
::restore() renv
Once done, exit R.
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:
$METHOD(PATH, HANDLER) app
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:
$get("/", \(req, res) {
app$send("Hello World!")
res })
Respond to POST request on the root route (/
), the application’s home page:
$post("/", \(req, res) {
app$send("Got a POST request")
res })
Respond to a PUT request to the /user
route:
$put("/user", \(req, res) {
app$send("Got a PUT request at /user")
res })
Respond to a DELETE request to the /user
route:
$delete("/user", \(req, res) {
app$send("Got a DELETE request at /user")
res })
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:
A simple JSON API
You’re now ready to build ✨a simple JSON API✨.