THEHORIZIAN
Ktor for Mobile Developers: Is it Easy to Learn Server Side Coding? Part-2
Backend for mobile engineers with Kotlin and Ktor
As you already check out my previous post about What is Ktor Framework? and How to get started?. In case of you didn’t please read this Ktor for Mobile Developers: Is it Easy to Learn Server Side Coding? Part-1.
So lets get deep dive into Ktor Framework and start solve some real world complex problem.
I am assuming you already created basic structure project.
In this section we are going to learn how to send response or accept the request in Json format.
For Json parsing we are using Jackson library. To install Json parsing library add gradle dependency in your build.gradle file.
implementation "io.ktor:ktor-jackson:$ktor_version"
Now install Jackson as ContentNegotiation
library in Application.module
.
install(ContentNegotiation) {
jackson {
enable(SerializationFeature.INDENT_OUTPUT)
}
}
In next step we are going to create Data Model class that will convert into Json structure and send it as response.
@JsonIgnoreProperties(ignoreUnknown = true)
data class User(
@JsonProperty("id") val id: UUID = UUID.randomUUID(),
@JsonProperty("email") val email: String="myemail@gmail.com",
@JsonProperty("first_name") val firstName: String="FirstName",
@JsonProperty("last_name") val lastName: String="LastName",
@JsonProperty("profile_image_url") val profileImageUrl: String?=null
)
To handle the GET request add the following code in your Application.module
routing {
get("/") {
call.respond(User())
}
/*---------------------*/
post { }
put { }
delete { }
}
Now run the server and open url on your browser localhost:8080
and now we get the Json response something like that.
{
"id" : "c4d93580-b719-41b5-bb05-be480b04a493",
"email" : "myemail@gmail.com",
"first_name" : "FirstName",
"last_name" : "LastName",
"profile_image_url" : null
}
So we successfully created the GET web API.
Now lets handle some POST web requests. We add post
method to handle the POST web request. In which we parse the request and match the FirstName of User. If User is matched then send a response as User Matched Successfully.
or if doesn’t then send response as User does not match.
routing {
get("/") {
call.respond(User())
}
post("") {
val userDto = call.receive<User>()
if ("FirstName" == userDto.firstName){
call.respondText { "User Matched Successfully." }
}else{
call.respondText { "User does not match." }
}
}
/*---------------------*/
put { }
delete { }
}
Now sent a POST request from the the postman
Hurrayyyy 😄 we successfully created GET and POST web API.
In the next Article we are going to learn how to communicate with your local database to insert data and fetch data from it.
To create basic project using Ktor framwork and what is the main feature of Ktor framwork? please visit here Ktor for Mobile Developers: Is it Easy to Learn Server Side Coding? Part-1.
Next Article will be coming soon…