Creating new Entities

Learrn how we can use the database connection to add a few entities in our Ktor application.

Adding a cat to our virtual shelter

Now our task is to add the first cat to our virtual shelter.

Following the REST principles, it should be a POST request, where the body of the request looks something like this:

{"name": "Meatloaf", "age": 4}

We’ll start by writing a new test in our AppTest.kt file:

@Test
fun `POST creates a new cat`() {
    ...
}

Backticks are a useful Kotlin feature that allow us to have spaces in the names of our functions. This helps us create descriptive test names. Next, let’s look at the body of our test, in the AppTest.kt file:

withTestApplication(Application::mainModule) {
     val response = handleRequest(HttpMethod.Post, "/cats") {
         addHeader(
            HttpHeaders.ContentType,
            ContentType.Application.FormUrlEncoded.toString()
         )
         setBody(
            listOf(
                "name" to "Meatloaf",
                "age" to 4.toString()
            ).formUrlEncode()
         )
     }.response
    
...