HTTP requests and responses: a worked reference
This page explains what a client sends and what your Mojara handler returns.
1. A successful GET request
Register a handler:
def status(req: Request) -> Response:
return Response.json('{"status":"ok"}')
app.get("/api/status", status)
Request it:
curl -i http://127.0.0.1:8000/api/status
The response should have HTTP status 200 and a JSON body:
{"status":"ok"}
2. A successful POST request
def create(req: Request) -> Response:
return Response.json('{"id":1,"created":true}', status=201)
app.post("/api/items", create)
Send:
curl -i -X POST http://127.0.0.1:8000/api/items
The handler responds with 201 Created, which indicates a resource was created.
3. A validation error
def update(req: Request) -> Response:
var title = req.json().get("title", "")
if len(title.strip()) == 0:
return Response.json('{"error":"title is required"}', status=422)
return Response.json('{"saved":true}')
A request missing title receives status 422 and a response explaining how to correct the input.
4. Authentication errors
Return 401 when the user has not authenticated; return 403 when the user is known but does not have permission.
{"error":"Authentication required"}
5. Other common status codes
| Status | Meaning | Example |
|---|---|---|
| 200 | Success | Read notes |
| 201 | Created | Add note |
| 302 | Redirect | Redirect old address |
| 400 | Malformed request | Broken JSON |
| 404 | Not found | Unknown note ID |
| 405 | Method not allowed | POST on GET-only path |
| 415 | Unsupported content type | XML sent to JSON endpoint |
| 422 | Validation failed | Empty required field |