Saving Data to a Database
Reading is only half the story. Let's handle form submissions so users can write data to your database. The pattern is always the same: read the body, validate, insert, respond.
Part of: Frame framework
A POST endpoint reads form fields from the request body:
POST "/messages" :
string content = json.get(req.form(), "content")
string author = json.get(req.form(), "author")
if content == ""
return http.respond(400, "text/plain", "Content is required")
string params = "[\"" + author + "\", \"" + content + "\"]"
db.query("INSERT INTO messages (author, content) VALUES (?, ?)", params)
return http.respond(201, "text/plain", "Message saved!")POST /messages (with form data) → 201 Message saved!
POST /messages (empty content) → 400 Content is requiredjson.get(req.form(), "field") reads a form field from the POST body. Validate before inserting — return 400 for bad input. Return 201 Created when a new resource is successfully created. The params order must match the ? placeholder order in your SQL.
A complete route pair: GET shows a form, POST handles it:
GET "/messages/new" :
html:
<form method="post" action="/messages">
<input name="author" placeholder="Your name">
<textarea name="content" placeholder="Message"></textarea>
<button type="submit">Send</button>
</form>
POST "/messages" :
string content = json.get(req.form(), "content")
string author = json.get(req.form(), "author")
if content == ""
return http.respond(400, "text/plain", "Content is required")
string params = "[\"" + author + "\", \"" + content + "\"]"
db.query("INSERT INTO messages (author, content) VALUES (?, ?)", params)
return http.respond(200, "text/html", "<p>Saved! <a href='/messages/new'>Send another</a></p>")GET /messages/new → HTML form
POST /messages → 200, confirmation messageGET shows the form, POST processes it. This GET-POST pair is the foundation of every web form. In production you'd redirect after POST to prevent double-submission, but this pattern is the right starting point.
- POST endpoints use json.get(req.form(), "fieldname") to read submitted form fields
- Validate input before writing to the database — return 400 for invalid data
- 201 Created is the conventional status for a successfully created resource
- Build params as a JSON array — values must match ? placeholder order