Skip to content

Guide Routing

Aaron edited this page Mar 14, 2023 · 1 revision

Routing

Very basic routing:

from express import express

app = express()

@app.get("/")
def helloWorld(req, res):
    res.send("hello world")

Route methods

An example of routes that are defined for the GET and the POST methods to the root of the app:

from express import express

app = express()

@app.get("/")
def getHome(req, res):
    res.send("GET request to the homepage")

@app.post("/")
def postHome(req, res):
    res.send("POST request to the homepage")

Express.py doesn't support all http methods. These are the ones supported: GET, POST, HEAD, PUT, DELETE & PATCH.

It's also possible to make a route for [b]all[/b] request methods:

@app.all("/")
def home(req, res):
    res.send("Idk what you did, but I like it :-)")

Route paths

Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions. In general, the route path gets changed into a regex string. The dot (.) gets escaped to \. (for regex). Please do not use any groups in your regex string as it messes up parameters 🥲

Here are some examples of route paths based on strings.

This route path will match requests to the root route, /.

@app.get("/")
def get(req, res):
    res.send("root")

This route path will match requests to /about.

@app.get("/about")
def get(req, res):
    res.send("about")

This route path will match requests to /random.text.

@app.get("/random.text")
def get(req, res):
    res.send("random.text")

Here are some examples of route paths based on string patterns.

This route path will match acd and abcd.

@app.get("/ab?cd")
def get(req, res):
    res.send('ab?cd')

This route path will match abcd, abbcd, abbbcd, and so on.

@app.get("/ab+cd")
def get(req, res):
    res.send('ab+cd')

This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.

@app.get("/ab*cd")
def get(req, res):
    res.send('ab*cd')

Route parameters

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.

Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }

To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.

@app.get("/users/:userId/books/:bookId")
def get(req, res):
    return(req.params)

Since the hyphen (-) and the dot (.) are interpreted literally, they can be used along with route parameters for useful purposes.

Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }
Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }

To have more control over the exact string that can be matched by a route parameter, you can append a regular expression in parentheses (()):

Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}

Route handlers

Handling a route is done through functions, which you can set through 2 ways

@app.get("/")
def get(req, res):
    res.send("hi")
def get(req, res):
    res.send("hi")
app.get("/", get)

It's also to add a function to multiple routes:

@app.get("/")
@app.get("/hello")
@app.head("/hello") # won't return body as HEAD should
def get(req, res):
    res.send("hi")
def get(req, res):
    res.send("hi")
app.get("/", get)
app.get("/hello", get)
app.head("/hello", get)

By routing like this, the following is possible.

Take this file system:

controllers
    |- post.py
    \- user.py
start.py
# post.py
def get(req, res):
    ...

def post(req, res):
    ...
# user.py
def get(req, res):
    ...

def post(req, res):
    ...

def put(req, res):
    ...

Then you can create your start.py file as:

from express import express

import controllers.post
import controllers.user


app = express()

app.get("/post", controllers.post.get)
app.post("/post", controller.post.post)

app.get("/user/:userId", controller.user.get)
app.post("/user", controller.user.post)
app.put("/user/:userId", controller.user.put)

app.route()

If you're this annoying.. You know what, just do whatever

@app.route("GET", "/")
def route(req, res):
    ...

^ I don't recommend

app.router()

this is what you've been waiting for

With this you can create a sort of "mini app" (express.js's words, not mine)

Here's a little example:

from express import express

app = express()
userRouter = app.router("/user")

@userRouter.get("") # /user
@userRouter.get("/") # /user/
def get(req, res):
    ...

@app.get("/") # /
def homePage(req, res):
    ...

@userRouter.get("/about") # /user/about
def getAbout(req, res):
    ...
Clone this wiki locally