Gebweb @ApiResource auto-CRUD
A 35-line Gebweb app that yields the full six-endpoint
- Path
gebweb/examples/widgets.gb- Category
- General
REST API for a Widget resource: list / create / read / replace /
patch / delete, plus auto-generated OpenAPI 3.1 + SwaggerUI at
/docs. The repository is an in-memory store so the example
needs no database.
Run:
geblang examples/widgets.gb
Then try:
curl localhost:8080/widgets
curl -XPOST localhost:8080/widgets -d '{"name":"Spanner","weight":5}'
curl localhost:8080/widgets/w1
curl -XPATCH localhost:8080/widgets/w1 -d '{"weight":42}'
open http://localhost:8080/docs
Source
import gebweb;
import gebweb.repository as repository;
import io;
@ApiResource("/widgets")
class Widget {
string id;
string name;
int weight;
static func repositoryClass(): any {
return WidgetRepository;
}
}
class WidgetRepository implements repository.Repository<Widget> {
dict<string, Widget> store;
func WidgetRepository() {
this.store = {};
}
func find(string id): ?Widget {
if (this.store.contains(id)) {
return this.store[id];
}
return null;
}
func list(repository.Page page): list<Widget> {
list<Widget> out = [];
let keys = this.store.keys();
int start = page.offset;
int end = start + page.size;
if (end > keys.length()) {
end = keys.length();
}
for (i in start..<end) {
out = out.push(this.store[keys[i]]);
}
return out;
}
func save(Widget entity): Widget {
if (entity.id == null || entity.id == "") {
entity.id = "w" + ((this.store.keys().length() + 1) as string);
}
this.store[entity.id] = entity;
return entity;
}
func delete(string id): void {
if (this.store.contains(id)) {
this.store.delete(id);
}
}
}
let app = gebweb.app([Widget]);
gebweb.setInfo(app, {
"title": "Widgets API",
"version": "0.1.0",
"description": "Auto-CRUD over an in-memory store. Generated by Gebweb @ApiResource.",
});
io.println("Widgets API on http://127.0.0.1:8080");
for (route in gebweb.routes(app)) {
io.println(" " + (route["method"] as string) + " " + (route["path"] as string));
}
io.println(" GET /docs (SwaggerUI)");
gebweb.serve(app, "127.0.0.1:8080");