-
You can generate a new project using Yeoman. Install the kue generator.
npm install -g generator-kue
-
Create a new directory and change into that directory.
mkdir widgets-api && cd widgets-api
-
Generate the project.
yo kue
-
Answer the prompts or leave the defaults. The rest of this guide assumes the defaults were used.
-
Start the app.
gradle run --continuous
-
Create a Widget.
curl -X POST -H "Content-Type: application/json" -d '{"name": "Foo", "color": "orange"}' "http://localhost:4567/widgets"
-
View a list of existing Widgets.
curl -X GET "http://localhost:4567/widgets"
-
Start exploring the code in
src/main/kotlin/com/widgets/Routes.kt
. This is where all of the Spark routes are mapped. Learn more about Spark routes. -
These routes are loaded by a Guice module defined at
src/main/kotlin/com/widgets/Module
. This is also where theWidgetController
and theWidgetService
is bound as well. Learn more about Guice. -
The application knows about the Guice module because the main class located inside of kue-core loads any modules defined in a config file for property
guice.modules
. Look inside ofsrc/main/resources/application.conf
for this application's config file. Learn more about Typesafe Config. -
Now let's add a route to GET a specific widget by ID. Start by adding the following function to
com.widgets.services.WidgetService
fun get(id: UUID) : Widget?
-
After saving, you'll notice in the console where you started the app with
gradle run --continuous
it reloaded after detecting the change. -
Add the implementation to
com.widgets.services.impl.DefaultWidgetService
override fun get(id: UUID): Widget? = Ebean.find(Widget::class.java).where().idEq(id).findUnique()
-
Add the controller action to
com.widgets.controllers.WidgetController
:val get = json(Route() { req, res -> val uuid = UUID.fromString(req.params("id")) val widget = widgetService.get(uuid) if (widget != null) { widgetResponse(widget) } else { res.status(404) } })
-
Add the route to
com.widgets.Route
get("/widgets/:id", widgetController.get)
-
You can now view a single Widget instance at
GET localhost:4567/widgets/<uuid-of-widget>