Tutorial: build a Notes API
In this tutorial you will create a Mojara project, add two endpoints, validate submitted data, and try both endpoints.
Step 1. Create your project
mojara new notes-api api
cd notes-api
Step 2. Write your application
from mojara import App, Request, Response
def list_notes(req: Request) -> Response:
return Response.json('{"notes":[{"id":1,"title":"Learn Mojo"}]}')
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":"New note"}', status=201)
def main() raises:
var app = App()
app.get("/api/notes", list_notes)
app.post("/api/notes", create_note)
app.run(port=8000)
The list_notes handler serves JSON for GET. The create_note handler reads JSON from POST and checks that title is present. App connects both handlers to the same URL using different methods.
Step 3. Run the API
mojara dev
Use the local address printed in your terminal.
Step 4. Read your notes
curl -i http://127.0.0.1:8000/api/notes
Expected body:
{"notes":[{"id":1,"title":"Learn Mojo"}]}
Step 5. Submit a new note
curl -i -X POST http://127.0.0.1:8000/api/notes \
-H "Content-Type: application/json" \
-d '{"title":"Read the routing guide"}'
The server responds with HTTP 201 and a JSON object representing the newly created note.
Step 6. Trigger a validation error
curl -i -X POST http://127.0.0.1:8000/api/notes \
-H "Content-Type: application/json" -d '{}'
Expected status: 422 and {"error":"title is required"}.
Step 7. Add persistence
The example returns fixed JSON to keep the first lesson simple. To store records, follow Models, SQLite, or PostgreSQL.
Step 8. Build
mojara build
mojara start
You have created, run, queried, validated and built an API. Next: Request handling, Authentication, and Deployment.