Build a JSON HTTP API
This tutorial creates a small JSON API with GET and POST endpoints.
1. Create an API project
mojara new notes-api api
cd notes-api
mojara dev
2. Add a GET endpoint
from mojara import App, Request, Response
def list_notes(req: Request) -> Response:
return Response.json('{"notes":[{"id":1,"title":"Learn Mojara"}]}')
def main() raises:
var app = App()
app.get("/api/notes", list_notes)
app.run(port=8000)
Run mojara dev and request:
curl -i http://127.0.0.1:8000/api/notes
Expected status: 200. The response body contains the notes array.
3. Add a POST endpoint
def create_note(req: Request) -> Response:
var data = req.json()
var title = data.get("title", "").strip()
if len(title) == 0:
return Response.json('{"error":"title is required"}', status=422)
return Response.json('{"id":2,"title":"Created"}', status=201)
Register app.post("/api/notes", create_note).
Try:
curl -i -X POST http://127.0.0.1:8000/api/notes \
-H "Content-Type: application/json" -d '{"title":"Created"}'
The example returns 201 Created. It demonstrates request handling; to persist notes, use the database service shown in Models.
4. API errors
Return 400 for malformed JSON, 401 when login is required, 403 for insufficient permission, 404 for missing records, 415 for unsupported content types, and 422 for invalid fields.
5. Explore OpenAPI
The Mojara reference application exposes an OpenAPI document at /openapi.json and interactive API explorer at /docs. These are application endpoints, distinct from this framework documentation website.
Next: Request parsing, Authentication, and API reference.