|
cwist
Modern C web framework with libttak runtime
|
This guide builds a small JSON blog API backed by CWIST's SQLite integration. It intentionally keeps SQL explicit so that the request, validation, and response boundaries are easy to inspect.
Create the table during application startup with a migration:
Use one handler per operation and parameterized routes for a post identifier.
| Method | Path | Action |
|---|---|---|
| GET | /posts | List posts |
| GET | /posts/:id | Read one post |
| POST | /posts | Create a post |
| PATCH | /posts/:id | Update title/body |
| DELETE | /posts/:id | Delete a post |
Read the route parameter with cwist_query_map_get(req->path_params, "id"). Treat it as untrusted input: parse the whole integer, reject non-positive values, and bind it to a prepared statement. Never interpolate JSON fields or route parameters into SQL.
Require title and body strings on create. Return 201 Created after an insert, 204 No Content after a successful delete, 400 Bad Request for a malformed request, and 404 Not Found when an id has no row. Always set Content-Type: application/json for JSON responses.
For browser clients, add CORS only for the origins you control and use CSRF middleware when cookie authentication is enabled. The existing WAF middleware is a useful additional boundary, but it does not replace parameterized SQL.
Use cwist_test_client to dispatch requests without binding a port. Cover the entire lifecycle: create, list, fetch, patch, delete, then fetch again and assert 404. Run the same tests against :memory: for fast isolation and a temporary on-disk database to exercise migrations.