DOCUMENTATION / CORE FRAMEWORK

Routing: GET, POST, JSON, and redirects

See the page-redirect tutorial for redirects after forms, login, and logout.

A route connects a URL and HTTP method to a Mojo function. This chapter extends the Hello World application by adding different routes.

1. Add an About page

Your homepage already uses app.get("/", home). Add another handler:

def about(req: Request) -> Response:
    return Response.html("<h1>About us</h1><p>Built with Mojara.</p>")

In main(), register the new handler:

app.get("/about", about)

Now visit http://127.0.0.1:8000/about. It shows the About page. Your homepage continues working.

2. Create three pages

The following example registers three GET routes:

from mojara import App, Request, Response

def home(req: Request) -> Response:
    return Response.html("<h1>Home</h1>")

def about(req: Request) -> Response:
    return Response.html("<h1>About</h1>")

def contact(req: Request) -> Response:
    return Response.html("<h1>Contact</h1>")

def main() raises:
    var app = App()
    app.get("/", home)
    app.get("/about", about)
    app.get("/contact", contact)
    app.run(port=8000)

Visit /, /about, and /contact to see the different pages.

3. Return JSON from a route

Web APIs usually return JSON instead of HTML. Add this handler:

def status(req: Request) -> Response:
    return Response.json('{"status":"ok","service":"mojara"}')

Register it:

app.get("/api/status", status)

Run the app and request the URL:

curl http://127.0.0.1:8000/api/status

Expected response body:

{"status":"ok","service":"mojara"}

4. Handle POST

A POST route accepts a submitted request. Define a handler and register it:

def add_message(req: Request) -> Response:
    return Response.json('{"message":"created"}', status=201)

def main() raises:
    var app = App()
    app.post("/api/messages", add_message)
    app.run(port=8000)

From another terminal:

curl -i -X POST http://127.0.0.1:8000/api/messages

The expected result is HTTP 201 Created, followed by a JSON response. This shows route registration; request-body parsing and validation are covered in Requests.

5. Redirect a URL

Use a redirect when an old address should send the visitor to a new page.

def go_home(req: Request) -> Response:
    return Response.redirect("/", status=302)

Register it:

app.get("/go", go_home)

Visit /go to be sent to /. You can inspect the redirect with:

curl -i http://127.0.0.1:8000/go

6. What to use and when

Task Example
Show a page app.get("/about", about)
Return API data Response.json(...)
Accept POST app.post("/api/messages", add_message)
Send a redirect Response.redirect("/")

You now have routes for multiple pages, JSON responses, POST requests, and redirects. Continue with Request data and validation.