Creating new Entities
Explore how to create new entities in a Ktor microservice by implementing POST endpoints in Kotlin. Learn to handle request parameters, insert data into the database using transactions, and ensure test consistency by cleaning the database before each test. This lesson guides you through writing and passing tests for adding new items in a RESTful service.
We'll cover the following...
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
assertEquals(HttpStatusCode.Created, ...