Examples: learn by building
The quickest way to learn Mojara is to create a small app, run it, then change its behavior.
Example 1. Hello World
from mojara import App, Request, Response
def hello(req: Request) -> Response:
return Response.html("<h1>Hello, Mojara!</h1>")
def main() raises:
var app = App()
app.get("/", hello)
app.run(port=8000)
Run mojara dev and open http://127.0.0.1:8000/.
Example 2. JSON status endpoint
def status(req: Request) -> Response:
return Response.json('{"service":"notes","status":"ok"}')
Register app.get("/api/status", status). Send curl http://127.0.0.1:8000/api/status and inspect the JSON response.
Example 3. Validate an email
def subscribe(req: Request) -> Response:
var email = req.json().get("email", "")
if "@" not in email:
return Response.json('{"error":"Provide a valid email"}', status=422)
return Response.json('{"subscribed":true}', status=201)
Register app.post("/api/subscribe", subscribe). Try:
curl -i -X POST http://127.0.0.1:8000/api/subscribe \
-H "Content-Type: application/json" -d '{"email":"amina@example.com"}'
Example 4. Query a database
from mojara.dbclient import PooledDatabase
var db = PooledDatabase("host=127.0.0.1 dbname=mojara_dev", capacity=2)
var lease = db.acquire()
var rows = lease.query("SELECT 1 AS number")
print(rows.cell(0, 0))
lease.release()
db.close()
This uses the PostgreSQL pool API. The full connection and transaction walkthrough is in PostgreSQL and Connection pools.
Choose your next lesson: Routes, Requests and forms, Databases, Deployment.