DOCUMENTATION / OVERVIEW

Organize a Mojara application

As your application grows, move HTTP handlers and database operations into separate modules. This lesson organizes a Notes app.

1. Start with one application

from mojara import App, Request, Response

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

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

This is fine for one route. As you add features, putting everything in one handler becomes hard to manage.

2. Add a model

struct Note:
    var id: Int
    var title: String

    def __init__(out self, id: Int, title: String):
        self.id = id
        self.title = title

The model represents a note independently of HTTP.

3. Add a database service

from mojara.dbclient import PooledDatabase

def fetch_notes(db: PooledDatabase) raises:
    var lease = db.acquire()
    var result = lease.query("SELECT id, title FROM notes")
    for i in range(result.rows()):
        print(result.cell(i, 0), result.cell(i, 1))
    lease.release()

This function is responsible for persistence, so a route does not need to know connection-pool details.

4. Add HTTP handlers

def list_notes(req: Request) -> Response:
    return Response.json('{"notes":[]}')

app.get("/api/notes", list_notes)

The handler decides the response format. Wire the database service to the handler when you add persistent notes.

5. Keep responsibilities separate

Layer Job
HTTP handlers Read requests and send responses
Models Represent application values
Services Implement business rules
Data access Query and update databases
Configuration Ports, connection strings, secrets

Start with Hello World, then continue to Models and Request parsing.