<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by José Luis González Sánchez on Medium]]></title>
        <description><![CDATA[Stories by José Luis González Sánchez on Medium]]></description>
        <link>https://medium.com/@joseluisgs?source=rss-e3e4edb52ca7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GCwbbSEhk_qUlNHIn3GBPQ.jpeg</url>
            <title>Stories by José Luis González Sánchez on Medium</title>
            <link>https://medium.com/@joseluisgs?source=rss-e3e4edb52ca7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:10:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joseluisgs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating your reactive REST API with Kotlin and Ktor part III]]></title>
            <link>https://medium.com/hyperskill/creating-your-reactive-rest-api-with-kotlin-and-ktor-part-iii-ae9803bca99a?source=rss-e3e4edb52ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9803bca99a</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[José Luis González Sánchez]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 15:46:08 GMT</pubDate>
            <atom:updated>2023-06-27T15:46:08.381Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Now it is time for this tutorial’s third and final part on creating a reactive REST service.</p><p>In the <a href="https://medium.com/hyperskill/creating-your-reactive-rest-api-with-kotlin-and-ktor-part-i-f217be55c0bf">first part</a>, we discussed the benefits of applying reactivity in our services and created our first endpoint using Ktor. In the second <a href="https://medium.com/hyperskill/creating-your-reactive-rest-api-with-kotlin-and-ktor-part-ii-7b6b087f61e7">part</a>, we implement some services: WebSockets, cache, storage, and use railway-oriented programming to manage our errors and test using mocks.</p><p>In the final part, we will focus on improving dependency injection, providing authentication and authorization mechanisms, documenting, and deploying our service in a container. Please visit previous tutorials first to understand some of the steps taken here and taken for granted or see how the code has been organized.</p><p>Like in other tutorials, the objective is to show you everything you will learn through the tracks on <a href="https://hyperskill.org/tracks?utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor3&amp;utm_term=27.07.2023">Hyperskill</a>. <strong>Hyperskill is the perfect place to delve deeper, expand your knowledge, and learn more about what is presented in this tutorial. It is the ideal platform for learning Kotlin technologies and using Ktor. Feel free to join and continue your learning journey</strong>. Remember that this code is pedagogical and shows many of the contents you will learn in a didactic and easy-to-read way. It is not intended to create the best production code in real environments. We know that many things can be done better, but they are exaggerated in the code so that, as a student, you can analyze the possibilities. Take it easy and check Hyperskill for more cool features for your Kotlin and Ktor services. Please feel free to experiment and modify what can improve your self-coding with different examples and reach your goals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNYTHm0fGgHP_UUalJuCUg.png" /></figure><h3>Dependency Injection with Koin</h3><p>Dependency injection is a design pattern used in software development to achieve loose coupling and promote modular, reusable code. In this pattern, the dependencies (external objects or services) required by a class are provided rather than the class creating or managing those dependencies themselves. There are several reasons why you should use dependency injection:</p><ul><li>Decoupling: By injecting dependencies, a class doesn’t need to know how to create or manage them. It decouples the class from the specific implementations of its dependencies, allowing for easier maintenance, testing, and future modifications.</li><li>Reusability: With dependency injection, dependencies can be reused across multiple classes or modules. It promotes code reuse, as the same dependency can be injected into different classes without duplicating code or creating tight dependencies.</li><li>Testability: Dependency injection facilitates unit testing by allowing dependencies to be easily mocked or replaced with test doubles. This enables isolated testing of individual components without complex setups or reliance on external resources.</li><li>Flexibility: Dependency injection makes it easier to swap out or change dependencies without modifying the classes that depend on them. This flexibility allows for easier adaptation to changing requirements or integrating new functionalities.</li></ul><p>In our service, we use <a href="https://insert-koin.io/">Koin</a>. Koin is a multiplatform lightweight dependency injection framework for Kotlin. It provides a simple and concise way to handle dependencies in your Kotlin projects. With Koin, you can easily define and inject dependencies without the need for complex configuration or boilerplate code. It offers a <a href="https://insert-koin.io/docs/reference/koin-core/dsl/">DSL</a> (Domain Specific Language) that allows you to declare and resolve dependencies readably and intuitively. We can use <a href="https://insert-koin.io/docs/setup/annotations">annotations</a> or a special version for <a href="https://insert-koin.io/docs/reference/koin-ktor/ktor">Ktor</a>. I love Koin because it adapts to what you need in any situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4dBIOwBb3mfOb7z28hOtg.png" /><figcaption>Koin logo by Kotzilla</figcaption></figure><p>We add the following dependencies in our <strong>build.gradle.kts</strong> file and sync the project. We’ll use annotations because if you’re new to Koin, the end goal is to make dependency injection easier and not learn all the DSL or other options that Koin offers, so we need to add the ksp plugin and options with Koin.</p><pre>plugins {<br>    kotlin(&quot;jvm&quot;) version &quot;1.8.21&quot;<br>    id(&quot;io.ktor.plugin&quot;) version &quot;2.3.1&quot;<br>    id(&quot;org.jetbrains.kotlin.plugin.serialization&quot;) version &quot;1.8.21&quot;<br>    // KSP for Koin Annotations<br>    id(&quot;com.google.devtools.ksp&quot;) version &quot;1.8.21-1.0.11&quot;<br>}<br><br>//...<br>dependencies {<br>// ...<br>// Koin for Dependency Injection<br>  implementation(&quot;io.insert-koin:koin-ktor:$koin_ktor_version&quot;) // Koin for Ktor<br>  implementation(&quot;io.insert-koin:koin-logger-slf4j:$koin_ktor_version&quot;) // Koin Logger<br>  implementation(&quot;io.insert-koin:koin-annotations:$koin_ksp_version&quot;) // Koin Annotations for KSP<br>  ksp(&quot;io.insert-koin:koin-ksp-compiler:$koin_ksp_version&quot;) // Koin KSP Compiler for KSP<br>}</pre><h4>Set up Koin</h4><p>Before we proceed, we need to configure Koin in Ktor. Thanks to its functionality for Ktor, this is an easy task. Once again, we’ll create a plugin called “Koin.” Since we’ll be using Koin with annotations, we don’t have to define anything else explicitly. All the dependencies will be defined using annotations, automatically creating a default module with all the pre-calculated dependencies. It’s straightforward and to the point. Finally, as we have done before, we’ll load this plugin into our application. I recommend you load it as the first plugin because these dependencies will be needed from the beginning.</p><pre>fun Application.configureKoin() {<br>  install(Koin) {<br>  slf4jLogger() // Logger<br>  defaultModule() // Default module with Annotations<br>}<br></pre><pre>fun Application.module() {<br>  configureKoin() // Configure the Koin plugin to inject dependencies<br>  configureWebSockets() // Configure the websockets plugin<br>  // ...<br>}</pre><h4>Configuration injection</h4><p>Let’s create a configuration class to encapsulate our service’s settings. This way, we can use different configuration files if needed. By doing this, we can easily inject this configuration. We will use the <strong><em>@Singleton</em></strong> annotation to ensure only one instance of it.</p><pre>@Singleton<br>class AppConfig {<br>  val applicationConfiguration: ApplicationConfig = ApplicationConfig(&quot;application.conf&quot;)<br>  // We can set here all the configuration we want from application.conf or from other sources<br>  // val applicationName: String = applicationConfiguration.property(&quot;ktor.application.name&quot;).getString()<br>  // val applicationPort: Int = applicationConfiguration.property(&quot;ktor.application.port&quot;).getString().toInt()<br>}</pre><h4>Preparing Repository and Services</h4><p>We use <strong><em>@Singleton</em></strong> in our repository and services</p><pre>@Singleton<br>class RacketsRepositoryImpl(<br>  private val dataBaseService: DataBaseService<br>) : RacketsRepository {<br>  //...<br>}<br><br>@Singleton<br>class DataBaseService(<br>  private val myConfig: AppConfig,<br>) {<br>  //...<br>}<br><br>@Singleton<br>class CacheService(<br>  private val myConfig: AppConfig,<br>) {<br>  //...<br>}<br><br>@Singleton<br>class StorageServiceImpl(<br>  private val myConfig: AppConfig<br>) : StorageService {<br>  //...<br>}<br><br>@Singleton<br>class RacketsServiceImpl(<br>  private val racketsRepository: RacketsRepository,<br>  private val cacheService: CacheService<br>) : RacketsService {<br>  //...<br>}</pre><h4>Injecting dependencies in routes</h4><p>Now, it’s time to inject dependencies into the routes. To do this, we can use <strong><em>get</em></strong>, which provides us with an immediate injection, or <strong><em>lazy</em></strong>, which provides us with a lazy injection, meaning the dependencies will be injected when we want to use them. In our case, the repository will be retrieved using <strong><em>get</em></strong> to have it immediately available. However, the storage will be <strong><em>lazy</em></strong> because it’s necessary once an image is uploaded. It’s important to note that this can vary depending on your specific problem or needs. As we can easily see, Koin will inject the dependencies we need wherever we need them, almost like magic. Isn’t it wonderful!</p><pre>// Dependency injection by Koin<br>val racketsService: RacketsService = get()<br>val storageService: StorageService by inject()</pre><h3>Authentication and Authorization with JWT</h3><p><strong>Authentication</strong> is verifying a user’s or entity’s identity, while <strong>authorization</strong> involves granting or denying access based on the user’s privileges. <a href="https://jwt.io/">JWT</a> (JSON Web Token) is a token-based authentication and authorization mechanism in web applications. JWT is a compact, self-contained token that consists of three parts: a header, a payload, and a signature. It securely carries information about the user’s identity and permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*Gsx2qgoi8OgzFBVaQ9-I5w.png" /><figcaption>JWT structure</figcaption></figure><p>The token is generated by the server upon successful authentication and is included in subsequent requests for authorization. When a request with a JWT is received, the server verifies the token’s authenticity using a secret key. It extracts the necessary information from the payload and determines whether the user has the required permissions to access the requested resources. By utilizing JWT, developers can implement a secure and scalable authentication and authorization system for services without needing a session state on the server side. It simplifies managing user sessions and enables stateless communication between client and server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*STlfA5M6VAQfET7zXoWGHA.png" /><figcaption>JWT auth</figcaption></figure><h4>Added dependencies</h4><p>The first step is to add the dependencies we need to handle JWT. Additionally, we will use Bcrypt to encrypt user passwords. Add the following dependencies to our <strong>build.gradle.kts</strong> file and sync the project.</p><pre>// Auth JWT<br>implementation(&quot;io.ktor:ktor-server-auth-jvm:$ktor_version&quot;)<br>implementation(&quot;io.ktor:ktor-server-auth-jwt-jvm:$ktor_version&quot;)<br>implementation(&quot;io.ktor:ktor-server-host-common-jvm:$ktor_version&quot;)<br>// BCrypt<br>implementation(&quot;com.ToxicBakery.library.bcrypt:bcrypt:$bcrypt_version&quot;)</pre><h4>Token configuration</h4><p>Let’s add our token configuration to our <strong>application.conf</strong> file.</p><pre># JWT<br>jwt {<br>  secret = &quot;IL0v3L34rn1ngKt0rWithJ0s3Lu1sGS4ndHyp3r$k1ll&quot;<br>  realm = &quot;rackets-ktor&quot;<br>  ## Expiration time: 3600s (1 hour)<br>  expiration = &quot;3600&quot;<br>  issuer = &quot;rackets-ktor&quot;<br>  audience = &quot;rackets-ktor-auth&quot;<br>}</pre><h4>Token Service</h4><p>The next step is to create a service that generates the tokens and allows us to verify them.</p><pre>sealed class TokenException(message: String) : RuntimeException(message) {<br>    class InvalidTokenException(message: String) : TokenException(message)<br>}<br><br>@Single<br>class TokensService(<br>    private val myConfig: AppConfig<br>) {<br><br>    val audience by lazy {<br>        myConfig.applicationConfiguration.propertyOrNull(&quot;jwt.audience&quot;)?.getString() ?: &quot;jwt-audience&quot;<br>    }<br>    val realm by lazy {<br>        myConfig.applicationConfiguration.propertyOrNull(&quot;jwt.realm&quot;)?.getString() ?: &quot;jwt-realm&quot;<br>    }<br>    private val issuer by lazy {<br>        myConfig.applicationConfiguration.propertyOrNull(&quot;jwt.issuer&quot;)?.getString() ?: &quot;jwt-issuer&quot;<br>    }<br>    private val expiresIn by lazy {<br>        myConfig.applicationConfiguration.propertyOrNull(&quot;jwt.tiempo&quot;)?.getString()?.toLong() ?: 3600<br>    }<br>    private val secret by lazy {<br>        myConfig.applicationConfiguration.propertyOrNull(&quot;jwt.secret&quot;)?.getString() ?: &quot;jwt-secret&quot;<br>    }<br><br>    init {<br>        logger.debug { &quot;Init tokens service with audience: $audience&quot; }<br>    }<br><br>    fun generateJWT(user: User): String {<br>        return JWT.create()<br>            .withAudience(audience)<br>            .withIssuer(issuer)<br>            .withSubject(&quot;Authentication&quot;)<br>            // user claims and other data to store<br>            .withClaim(&quot;username&quot;, user.username)<br>            .withClaim(&quot;usermail&quot;, user.email)<br>            .withClaim(&quot;userId&quot;, user.id.toString())<br>            // expiration time from currentTimeMillis + (tiempo times in seconds) * 1000 (to millis)<br>            .withExpiresAt(Date(System.currentTimeMillis() + expiresIn * 1000L))<br>            // sign with secret<br>            .sign(<br>                Algorithm.HMAC512(secret)<br>            )<br>    }<br><br>    fun verifyJWT(): JWTVerifier {<br><br>        return try {<br>            JWT.require(Algorithm.HMAC512(secret))<br>                .withAudience(audience)<br>                .withIssuer(issuer)<br>                .build()<br>        } catch (e: Exception) {<br>            throw TokenException.InvalidTokenException(&quot;Invalid token&quot;)<br>        }<br>    }<br>}</pre><h4>Users Repository</h4><p>Now we need a user repository, so we need our user model.</p><pre>data class User(<br>    val id: Long = NEW_USER,<br>    val name: String,<br>    val email: String,<br>    val username: String,<br>    val password: String,<br>    val avatar: String = DEFAULT_IMAGE,<br>    val role: Role = USER,<br>    val createdAt: LocalDateTime = LocalDateTime.now(),<br>    val updatedAt: LocalDateTime = LocalDateTime.now(),<br>    val deleted: Boolean = false<br>) {<br><br>    companion object {<br>        const val NEW_USER = -1L<br>        const val DEFAULT_IMAGE = &quot;https://i.imgur.com/fIgch2x.png&quot;<br>    }<br><br>    enum class Role {<br>        USER, ADMIN<br>    }<br>}</pre><p>We also need our tables and entities and their mappers to store them in the database.</p><pre>object UserTable : H2Table&lt;UserEntity&gt;(&quot;users&quot;) {<br>    // Autoincrement and primary key<br>    val id = autoIncrementBigInt(UserEntity::id).primaryKey()<br><br>    // Other fields<br>    val name = varchar(UserEntity::name)<br>    val email = varchar(UserEntity::email)<br>    val username = varchar(UserEntity::username)<br>    val password = varchar(UserEntity::password)<br>    val avatar = varchar(UserEntity::avatar)<br>    val role = varchar(UserEntity::role)<br><br>    // metadata<br>    val createdAt = timestamp(UserEntity::createdAt, &quot;created_at&quot;)<br>    val updatedAt = timestamp(UserEntity::updatedAt, &quot;updated_at&quot;)<br>    val deleted = boolean(UserEntity::deleted)<br>}<br><br>data class UserEntity(<br>    // Id<br>    val id: Long?, //<br><br>    // data<br>    val name: String,<br>    val email: String,<br>    val username: String,<br>    val password: String,<br>    val avatar: String = User.DEFAULT_IMAGE,<br>    val role: String = User.Role.USER.name,<br>    val createdAt: LocalDateTime = LocalDateTime.now(),<br>    val updatedAt: LocalDateTime = LocalDateTime.now(),<br>    val deleted: Boolean = false<br>)</pre><p>Finally, we will add some sample data using <strong>BCrypt</strong> to make some users available. In our database service, we will instruct it to create the user tables and load this data, as in previous tutorials. We need Bcrypt to hash passwords because it provides a secure and computationally expensive hashing algorithm that helps protect user passwords from being easily compromised or decrypted by potential attackers, and we store hashed passwords in our database.</p><p>It’s time to code our repository to handle users and implement the <strong>CRUD</strong> operations for them.</p><pre>@Singleton<br>class UsersRepositoryImpl(<br>  private val dataBaseService: DataBaseService<br>) : UsersRepository {<br><br><br>  override suspend fun findAll(): Flow&lt;User&gt; = withContext(Dispatchers.IO) {<br>    logger.debug { &quot;findAll&quot; }<br>  <br>    return@withContext (dataBaseService.client selectFrom UserTable).fetchAll()<br>    .map { it.toModel() }<br>  }<br>  <br>  // . . .<br>  <br>  <br>  override suspend fun checkUserNameAndPassword(username: String, password: String): User? =<br>  withContext(Dispatchers.IO) {<br>    val user = findByUsername(username)<br>    return@withContext user?.let {<br>    if (Bcrypt.verify(password, user.password.encodeToByteArray())) {<br>      return@withContext user<br>    }<br>    return@withContext null<br>    }<br>  }<br>  // . . .<br>  override suspend fun findById(id: Long): User? = withContext(Dispatchers.IO) {<br>    logger.debug { &quot;findById: Buscando usuario con id: $id&quot; }<br>  <br>    return@withContext (dataBaseService.client selectFrom UserTable<br>      where UserTable.id eq id<br>      ).fetchFirstOrNull()?.toModel()<br>   }<br>  // . . .<br>}</pre><h4>Users Service</h4><p>Now it’s time for our service, where we can also implement caching for users and follow a similar approach as we did in the previous tutorial with rackets with <strong>Railway-oriented Programming</strong> (UserErrors).</p><pre>@Singleton<br>class UsersServiceImpl(<br>  private val usersRepository: UsersRepository,<br>  private val cacheService: CacheService<br>) : UsersService {<br><br>  override suspend fun findAll(): Flow&lt;User&gt; {<br>    logger.debug { &quot;findAll: search all users&quot; }<br>    return usersRepository.findAll()<br>  }<br>  <br>  override suspend fun findById(id: Long): Result&lt;User, UserError&gt; {<br>    logger.debug { &quot;findById: search user by id&quot; }<br><br>    // find in cache if not found in repository<br>    return cacheService.users.get(id)?.let {<br>        logger.debug { &quot;findById: found in cache&quot; }<br>        Ok(it)<br>    } ?: run {<br>        usersRepository.findById(id)?.let { user -&gt;<br>            logger.debug { &quot;findById: found in repository&quot; }<br>            cacheService.users.put(id, user)<br>            Ok(user)<br>        } ?: Err(UserError.NotFound(&quot;User with id $id not found&quot;))<br>    }<br>  }<br><br>  override suspend fun findByUsername(username: String): Result&lt;User, UserError&gt; {<br>    logger.debug { &quot;findById: search user by username&quot; }<br>    // find in cache if not found in repository<br>    return usersRepository.findByUsername(username)?.let { user -&gt;<br>      logger.debug { &quot;findById: found in repository&quot; }<br>      cacheService.users.put(user.id, user)<br>      Ok(user)<br>    } ?: Err(UserError.NotFound(&quot;User with username: $username not found&quot;))<br>  }<br>  // . . .<br>}</pre><h4>Configure JWT Plugin</h4><p>Before we proceed, we need to configure the <a href="https://ktor.io/docs/jwt.html">JWT plugin</a>. This way, we can intercept <strong>JWT</strong> tokens using our token service to analyze their validity. In <strong>Security.kt</strong> Plugin.</p><pre>fun Application.configureSecurity() {<br>  // Inject the token service<br>  val jwtService: TokensService by inject()<br><br>  authentication {<br>      jwt {<br>          // Load the token verification config<br>          verifier(jwtService.verifyJWT())<br>          // With realm we can get the token from the request<br>          realm = jwtService.realm<br>          validate { credential -&gt;<br>              // If the token is valid, it also has the indicated audience,<br>              // and has the user&#39;s field to compare it with the one we want<br>              // return the JWTPrincipal, otherwise return null<br>              if (credential.payload.audience.contains(jwtService.audience) &amp;&amp;<br>                  credential.payload.getClaim(&quot;username&quot;).asString().isNotEmpty()<br>              )<br>                  JWTPrincipal(credential.payload)<br>              else null<br>          }<br><br>          challenge { defaultScheme, realm -&gt;<br>              throw TokenException.InvalidTokenException(&quot;Invalid or expired token&quot;)<br>          }<br>      }<br>  }<br><br>}</pre><p>We can also use <strong>StatusPages</strong> to automatically return error responses when encountering invalid or expired JWT tokens.</p><pre>// Token is not valid or expired<br>exception&lt;TokenException.InvalidTokenException&gt; { call, cause -&gt;<br>  call.respond(HttpStatusCode.Unauthorized, cause.message.toString())<br>}</pre><h4>Users Routes</h4><p>Now it’s time to create the routes to allow users to register, log in or perform specific operations based on their roles. We are going to inject the dependencies you need.</p><p>We can use <a href="https://ktor.io/docs/authentication.html#authenticate-route"><strong>authenticate</strong></a> to indicate that those routes or requests should be authenticated. Additionally, we can obtain the token data using <strong>JWTPrincipal</strong>.</p><pre>authenticate {<br>  // Get the user info --&gt; GET /api/users/me (with token)<br>  get(&quot;/me&quot;) {<br>      logger.debug { &quot;GET Me /$ENDPOINT/me&quot; }<br><br>      // Token came with principal (authenticated) user in its claims<br>      // Be careful, it comes with quotes!!!<br>      val userId = call.principal&lt;JWTPrincipal&gt;()<br>          ?.payload?.getClaim(&quot;userId&quot;)<br>          .toString().replace(&quot;\&quot;&quot;, &quot;&quot;).toLong()<br><br>      usersService.findById(userId)<br>          .mapBoth(<br>              success = { call.respond(HttpStatusCode.OK, it.toDto()) },<br>              failure = { handleUserError(it) }<br>          )<br>  }<br>  // Get all users --&gt; GET /api/users/list (with token and only if you are admin)<br>  get(&quot;/list&quot;) {<br>      logger.debug { &quot;GET Users /$ENDPOINT/list&quot; }<br><br>      val userId = call.principal&lt;JWTPrincipal&gt;()<br>          ?.payload?.getClaim(&quot;userId&quot;)<br>          .toString().replace(&quot;\&quot;&quot;, &quot;&quot;).toLong()<br><br>      usersService.isAdmin(userId)<br>          .onSuccess {<br>              usersService.findAll().toList()<br>                  .map { it.toDto() }<br>                  .let { call.respond(HttpStatusCode.OK, it) }<br>          }.onFailure {<br>              handleUserError(it)<br>          }<br>  }<br>  //..<br>}</pre><p>Now, with Postman, we can use our tokens to make requests. You can obtain <strong>401 if you are unauthorized or 403 Forbidden if you are not admin</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*2b8FdCILdVYtp0tPuoAOqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*WCG3T3UjGkbOFLz6jMVSFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*S4Kc9smHLvqsphosKBL4_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*zLWjGhkTtyQB7FdkEdKWHg.png" /></figure><h3>SSL/TSL</h3><p>We have a problem, and you can see that our password when logging in needs to be end-to-end encrypted. SSL/TLS (Secure Sockets Layer/Transport Layer Security) is crucial in service for the following reasons:</p><ul><li>Encryption: SSL/TLS ensures secure communication by encrypting data transmission and preventing unauthorized access to sensitive information.</li><li>Data Integrity: SSL/TLS verifies that data remains unchanged during transit, preventing tampering or modification by malicious actors.</li><li>Authentication: SSL/TLS enables server authentication, validating the server’s identity to establish trust with clients and prevent impersonation.</li><li>Trust and Credibility: Implementing SSL/TLS builds trust and credibility with users, assuring them that their data is protected and fostering a positive user experience.</li><li>Compliance: SSL/TLS is often required for regulatory compliance, ensuring the protection of sensitive data and adherence to industry standards and regulations.</li></ul><p><strong>In this example, we will use self-signed certificates but do not use them in production. We are only doing this to demonstrate how to secure our communications</strong>.</p><p>Let’s create a folder called <strong>cert,</strong> and with this script, we will generate our keystore containing the server’s private and public keys and their certificate for advertising to clients.</p><pre>#!/usr/bin/env bash<br>## Server KeyStore: Private Key + Public Certificate (PKCS12)<br>keytool -genkeypair -alias serverKeyPair -keyalg RSA -keysize 4096 -validity 365 -storetype PKCS12 -keystore server_keystore.p12 -storepass 1234567</pre><h4>Added dependencies</h4><p>We add the following dependencies in our <strong>build.gradle.kts</strong> file and sync the project.</p><pre>// SSL/TLS<br>implementation(&quot;io.ktor:ktor-network-tls-certificates:$ktor_version&quot;)</pre><h4>Configure SSL/TS</h4><p>Now it is time to configure the <a href="https://ktor.io/docs/ssl.html">service</a>. We will add this option in our configuration file application.conf with the secure port and SSL options.</p><pre>ktor {<br>    deployment {<br>        port = 8080<br>        port = ${?PORT}<br>        ## SSL, you need to enable it<br>        sslPort = 8083<br>        sslPort = ${?SSL_PORT}<br>    }<br><br>    # Configure the main module<br>    application {<br>        modules = [ joseluisgs.dev.ApplicationKt.module ]<br>    }<br><br>    ## Development mode<br>    # Enable development mode. Recommended to set it via -Dktor.deployment.environment=development<br>    # development = true<br>    deployment {<br>        ## Watch for changes in this directory and automatically reload the application if any file changes.<br>        watch = [ classes, resources ]<br>    }<br><br>    ## Modo de ejecución<br>    environment = dev<br>    environment = ${?KTOR_ENV}<br><br>    ## To enable SSL, you need to generate a certificate and configure it here<br>    security {<br>        ssl {<br>           keyStore = cert/server_keystore.p12<br>           keyAlias = &quot;serverKeyPair&quot;<br>           keyStorePassword = &quot;1234567&quot;<br>           privateKeyPassword = &quot;1234567&quot;<br>        }<br>    }<br>}</pre><p>From now on, all requests to the secure port with Postman will be encrypted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*9uy87-i-QYG-J0fb7Sh5ug.png" /></figure><h3>Document our service</h3><p>It’s time to document our service. We will use Dokka to generate Kotlin code documentation and Swagger for API documentation.</p><p>Dokka is a documentation engine for Kotlin. It allows developers to generate comprehensive documentation for their code, including classes, functions, properties, and more. Dokka parses the source code and generates HTML or other documentation formats that developers can easily browse and access.</p><p>Swagger is an open-source framework and a powerful tool for designing, building, documenting, and consuming RESTful APIs. It provides a suite of tools that enable developers to define API specifications using the OpenAPI Specification (OAS), formerly known as Swagger Specification. With Swagger, developers can create interactive API documentation that includes details about endpoints, request/response formats, parameters, authentication requirements, and more. It also allows for testing and exploring APIs directly from the documentation.</p><h4>Added dependencies</h4><p>We added the following dependencies in our <strong>build.gradle.kts</strong> file and sync the project. For Dokka, add the plugin.</p><pre>// Dokka for documentation<br>id(&quot;org.jetbrains.dokka&quot;) version &quot;1.8.10&quot;</pre><p>We will use the following library for Swagger: Ktor Swagger, which offers an extension function to document our routes.</p><pre>repositories {<br>  mavenCentral()<br>  maven(&quot;https://jitpack.io&quot;) // For Swagger UI<br>}</pre><p>We will need CORS options</p><pre>// CORS<br>implementation(&quot;io.ktor:ktor-server-cors:$ktor_version&quot;)<br>// To generate Swagger UI<br>implementation(&quot;io.github.smiley4:ktor-swagger-ui:$ktor_swagger_ui_version&quot;)</pre><h3>Configure Plugins</h3><p>We need to configure the <strong>CORS plugin</strong>. CORS (Cross-Origin Resource Sharing) is a security mechanism implemented in web browsers that control access to resources from different origins. It allows or restricts cross-origin requests, helping to prevent unauthorized access and protect user data. Here is an example.</p><pre>fun Application.configureCors() {<br>  install(CORS) {<br>    anyHost() // Allow from any host<br>    allowHeader(HttpHeaders.ContentType) // Allow Content-Type header<br>    allowHeader(HttpHeaders.Authorization)<br>    allowHost(&quot;client-host&quot;) // Allow requests from client-host<br>  }<br>}</pre><p>Now we configure the<strong> Swagger plugin</strong> to configure the global options and detect the endpoint.</p><pre>fun Application.configureSwagger() {<br>  // https://github.com/SMILEY4/ktor-swagger-ui/wiki/Configuration<br>  // http://xxx/swagger/<br>  install(SwaggerUI) {<br>      swagger {<br>          swaggerUrl = &quot;swagger&quot;<br>          forwardRoot = false<br>      }<br>      info {<br>          title = &quot;Ktor Hyperskill Reactive API REST&quot;<br>          version = &quot;latest&quot;<br>          description = &quot;Example of a Ktor API REST using Kotlin and Ktor&quot;<br>          contact {<br>              name = &quot;José Luis González Sánchez&quot;<br>              url = &quot;https://github.com/joseluisgs&quot;<br>          }<br>          license {<br>              name = &quot;Creative Commons Attribution-ShareAlike 4.0 International License&quot;<br>              url = &quot;https://joseluisgs.dev/docs/license/&quot;<br>          }<br>      }<br><br>      schemasInComponentSection = true<br>      examplesInComponentSection = true<br>      automaticTagGenerator = { url -&gt; url.firstOrNull() }<br>      // We can filter paths and methods<br>      pathFilter = { method, url -&gt;<br>          url.contains(&quot;rackets&quot;)<br>          //(method == HttpMethod.Get &amp;&amp; url.firstOrNull() == &quot;api&quot;)<br>          // || url.contains(&quot;test&quot;)<br>      }<br><br>      // We can add security<br>      securityScheme(&quot;JWT-Auth&quot;) {<br>          type = AuthType.HTTP<br>          scheme = AuthScheme.BEARER<br>          bearerFormat = &quot;jwt&quot;<br>      }<br>  }<br>}</pre><p>We add these plugins to our Application module</p><pre>fun Application.module() {<br>  configureKoin() // Configure the Koin plugin to inject dependencies<br>  configureSecurity() // Configure the security plugin with JWT<br>  configureWebSockets() // Configure the websockets plugin<br>  configureSerialization() // Configure the serialization plugin<br>  configureRouting() // Configure the routing plugin<br>  configureValidation() // Configure the validation plugin<br>  configureStatusPages() // Configure the status pages plugin<br>  configureCompression() // Configure the compression plugin<br>  configureCors() // Configure the CORS plugin<br>  configureSwagger() // Configure the Swagger plugin<br>}</pre><h4>Document with Dokka</h4><p>To document with Dokka, we can make use of your <a href="https://kotlinlang.org/docs/kotlin-doc.html">annotations</a>.</p><pre>/**<br>* Find by ID, if not exists return null<br>* @param id Long ID<br>* @return Racket? Racket or null<br>*/<br>override suspend fun findById(id: Long): Racket? = withContext(Dispatchers.IO) {<br>  logger.debug { &quot;findById: $id&quot; }<br><br>  return@withContext (dataBaseService.client selectFrom RacketTable<br>  where RacketTable.id eq id)<br>  .fetchFirstOrNull()?.toModel()<br>}</pre><p>Now with Gradle → Documentation, you can generate Dokka docs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGHW0Kz2fo5ybGw1K7nGcA.png" /></figure><h4>Document with Swagger</h4><p>To document with Swagger, we can complete our routes and petitions with docs options.</p><pre>routing {<br>  route(&quot;/$ENDPOINT&quot;) {<br><br>      // Get all racket --&gt; GET /api/rackets<br>      get({<br>          description = &quot;Get All Rackets&quot;<br>          request {<br>              queryParameter&lt;Int&gt;(&quot;page&quot;) {<br>                  description = &quot;page number&quot;<br>                  required = false // Optional<br>              }<br>              queryParameter&lt;Int&gt;(&quot;perPage&quot;) {<br>                  description = &quot;number of elements per page&quot;<br>                  required = false // Optional<br>              }<br>          }<br>          response {<br>              default {<br>                  description = &quot;List of Rackets&quot;<br>              }<br>              HttpStatusCode.OK to {<br>                  description = &quot;List of Rackets&quot;<br>                  body&lt;List&lt;RacketResponse&gt;&gt; { description = &quot;List of Rackets&quot; }<br>              }<br>          }<br>      }) {<br>          // QueryParams: rackets?page=1&amp;perPage=10<br>          call.request.queryParameters[&quot;page&quot;]?.toIntOrNull()?.let {<br>              val page = if (it &gt; 0) it else 0<br>              val perPage = call.request.queryParameters[&quot;perPage&quot;]?.toIntOrNull() ?: 10<br><br>              logger.debug { &quot;GET ALL /$ENDPOINT?page=$page&amp;perPage=$perPage&quot; }<br><br>              racketsService.findAllPageable(page, perPage)<br>                  .toList()<br>                  .run {<br>                      call.respond(HttpStatusCode.OK, RacketPage(page, perPage, this.toResponse()))<br>                  }<br><br>          } ?: run {<br>              logger.debug { &quot;GET ALL /$ENDPOINT&quot; }<br><br>              racketsService.findAll()<br>                  .toList()<br>                  .run { call.respond(HttpStatusCode.OK, this.toResponse()) }<br>          }<br>      }<br><br>      // Get one racket by id --&gt; GET /api/rackets/{id}<br>      get(&quot;{id}&quot;, {<br>          description = &quot;Get Racket by ID&quot;<br>          request {<br>              pathParameter&lt;Long&gt;(&quot;id&quot;) {<br>                  description = &quot;Racket ID&quot;<br>              }<br>          }<br>          response {<br>              HttpStatusCode.OK to {<br>                  description = &quot;Racket&quot;<br>                  body&lt;RacketResponse&gt; { description = &quot;Racket&quot; }<br>              }<br>              HttpStatusCode.NotFound to {<br>                  description = &quot;Racket not found&quot;<br>                  body&lt;RacketError.NotFound&gt; { description = &quot;Racket not found&quot; }<br>              }<br>          }<br>      }) {<br>          logger.debug { &quot;GET BY ID /$ENDPOINT/{id}&quot; }<br><br>          call.parameters[&quot;id&quot;]?.toLong()?.let { id -&gt;<br>              racketsService.findById(id).mapBoth(<br>                  success = { call.respond(HttpStatusCode.OK, it.toResponse()) },<br>                  failure = { handleRacketErrors(it) }<br>              )<br>          }<br>      }<br>//...<br>}</pre><p>Now we can watch the Swagger doc at <a href="http://0.0.0.0:8080/swagger">http://0.0.0.0:8080/swagger</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OF1d1p_t8zB9qOJ-KCOyw.png" /></figure><h3>Testing routes</h3><p>In previous tutorials, we have learned how to test our repositories or services, either through unit tests or tests with doubles using mocks. Now it’s time to test our endpoints. We have used <strong>Postman</strong>, which is excellent for these scenarios and can be optimized for efficient testing of endpoints. But <strong>Ktor</strong> provides a particular <a href="https://ktor.io/docs/testing.html">testing engine</a> that doesn’t create a web server, doesn’t bind to sockets, and doesn’t make any real HTTP requests. Instead, it hooks directly into internal mechanisms and processes an application call. This results in quicker test execution compared to running a complete web server for testing. Knowing how to use such tools to improve our deployments and optimize tests is great.</p><h4>Added dependencies</h4><p>Add the following dependencies in our <strong>build.gradle.kts</strong> file and sync the project.</p><pre>// Ktor Test<br>testImplementation(&quot;io.ktor:ktor-server-test-host:$ktor_version&quot;)<br>implementation(&quot;io.ktor:ktor-client-content-negotiation:$ktor_version&quot;) // For testing with Ktor Client JSON<br>implementation(&quot;io.ktor:ktor-client-auth:$ktor_version&quot;) // For testing with Ktor Client Auth JWT</pre><h4>Testing</h4><p>Now we can test the desired routes quickly and efficiently using this method. You can pass tokens as a header or process multipart requests to upload images.</p><p>An example with rackets</p><pre>private val json = Json { ignoreUnknownKeys = true }<br><br>@TestInstance(TestInstance.Lifecycle.PER_CLASS)<br>@TestMethodOrder(MethodOrderer.OrderAnnotation::class)<br>class RacketsRoutesKtTest {<br>  // Load configuration from application.conf<br>  private val config = ApplicationConfig(&quot;application.conf&quot;)<br><br>  val racket = RacketRequest(<br>      brand = &quot;Test&quot;,<br>      model = &quot;Test&quot;,<br>      price = 10.0,<br>      numberTenisPlayers = 1,<br>  )<br><br>  // New we can user it to test routes with Ktor<br>  @Test<br>  @Order(1)<br>  fun testGetAll() = testApplication {<br>      // Set up the test environment<br>      environment { config }<br><br>      // Launch the test<br>      val response = client.get(&quot;/api/rackets&quot;)<br><br>      // Check the response and the content<br>      assertEquals(HttpStatusCode.OK, response.status)<br>      // Check the content if we want<br>      // val result = response.bodyAsText()<br>      // val list = json.decodeFromString&lt;List&lt;RacketResponse&gt;&gt;(result)<br>      // ....<br><br>  }<br>//...<br>  @Test<br>  @Order(4)<br>  fun testPut() = testApplication {<br>      environment { config }<br>  <br>      val client = createClient {<br>          install(ContentNegotiation) {<br>              json()<br>          }<br>      }<br>  <br>      // Create<br>      var response = client.post(&quot;/api/rackets&quot;) {<br>          contentType(ContentType.Application.Json)<br>          setBody(racket)<br>      }<br>  <br>      // Take the id of the result<br>      var dto = json.decodeFromString&lt;RacketResponse&gt;(response.bodyAsText())<br>  <br>      // Update<br>      response = client.put(&quot;/api/rackets/${dto.id}&quot;) {<br>          contentType(ContentType.Application.Json)<br>          setBody(racket.copy(brand = &quot;TestBrand2&quot;, model = &quot;TestModel2&quot;))<br>      }<br>  <br>      // Check that the response and the content is correct<br>      assertEquals(HttpStatusCode.OK, response.status)<br>      val result = response.bodyAsText()<br>      dto = json.decodeFromString&lt;RacketResponse&gt;(result)<br>      assertAll(<br>          { assertEquals(&quot;TestBrand2&quot;, dto.brand) },<br>          { assertEquals(&quot;TestModel2&quot;, dto.model) },<br>          { assertEquals(racket.price, dto.price) },<br>          { assertEquals(racket.numberTenisPlayers, dto.numberTenisPlayers) },<br>      )<br>  }<br><br>  @Test<br>  @Order(5)<br>  fun testPutNotFound() = testApplication {<br>      environment { config }<br>  <br>      val client = createClient {<br>          install(ContentNegotiation) {<br>              json()<br>          }<br>      }<br>  <br>      val response = client.put(&quot;/api/rackets/-1&quot;) {<br>          contentType(ContentType.Application.Json)<br>          setBody(racket.copy(brand = &quot;TestBrand2&quot;, model = &quot;TestModel2&quot;))<br>      }<br>  <br>      assertEquals(HttpStatusCode.NotFound, response.status)<br>  }<br>// ...<br>}</pre><p>Or using JWT with users</p><pre>private val json = Json { ignoreUnknownKeys = true }<br><br>@TestInstance(TestInstance.Lifecycle.PER_CLASS)<br>@TestMethodOrder(MethodOrderer.OrderAnnotation::class)<br>class UsersRoutesKtTest {<br>  private val config = ApplicationConfig(&quot;application.conf&quot;)<br><br>  val userDto = UserCreateDto(<br>      name = &quot;Test&quot;,<br>      email = &quot;test@test.com&quot;,<br>      username = &quot;test&quot;,<br>      password = &quot;test12345&quot;,<br>      avatar = User.DEFAULT_IMAGE,<br>      role = User.Role.USER<br>  )<br><br>  val userLoginDto = UserLoginDto(<br>      username = &quot;test&quot;,<br>      password = &quot;test12345&quot;<br>  )<br><br>  val userLoginAdminDto = UserLoginDto(<br>      username = &quot;pepe&quot;,<br>      password = &quot;pepe1234&quot;<br>  )<br><br>  @Test<br>  @Order(1)<br>  fun registerUserTest() = testApplication {<br>      // Set up the test environment<br>      environment { config }<br>      val client = createClient {<br>          install(ContentNegotiation) {<br>              json()<br>          }<br>      }<br><br>      // Launch the test<br>      val response = client.post(&quot;/api/users/register&quot;) {<br>          contentType(ContentType.Application.Json)<br>          setBody(userDto)<br>      }<br><br>      // Check the response and the content<br>      assertEquals(response.status, HttpStatusCode.Created)<br>      val res = json.decodeFromString&lt;UserDto&gt;(response.bodyAsText())<br>      assertAll(<br>          { assertEquals(res.name, userDto.name) },<br>          { assertEquals(res.email, userDto.email) },<br>          { assertEquals(res.username, userDto.username) },<br>          { assertEquals(res.avatar, userDto.avatar) },<br>          { assertEquals(res.role, userDto.role) },<br>      )<br>  }<br><br><br>  @Test<br>  @Order(2)<br>  fun login() = testApplication {<br>      environment { config }<br>      val client = createClient {<br>          install(ContentNegotiation) {<br>              json()<br>          }<br>      }<br><br>      client.post(&quot;/api/users/register&quot;) {<br>          contentType(ContentType.Application.Json)<br>          setBody(userDto)<br>      }<br><br>      val responseLogin = client.post(&quot;/api/users/login&quot;) {<br>          contentType(ContentType.Application.Json)<br>          setBody(userLoginDto)<br>      }<br><br>      assertEquals(responseLogin.status, HttpStatusCode.OK)<br>      val res = json.decodeFromString&lt;UserWithTokenDto&gt;(responseLogin.bodyAsText())<br>      assertAll(<br>          { assertEquals(res.user.name, userDto.name) },<br>          { assertEquals(res.user.email, userDto.email) },<br>          { assertEquals(res.user.username, userDto.username) },<br>          { assertEquals(res.user.avatar, userDto.avatar) },<br>          { assertEquals(res.user.role, userDto.role) },<br>          { assertNotNull(res.token) },<br>      )<br>  }<br><br>  @Test<br>  @Order(3)<br>  fun meInfoTest() = testApplication {<br>      environment { config }<br><br>      var client = createClient {<br>          install(ContentNegotiation) {<br>              json()<br>          }<br>      }<br><br>      var response = client.post(&quot;/api/users/register&quot;) {<br>          contentType(ContentType.Application.Json)<br>          setBody(userDto)<br>      }<br><br>      response = client.post(&quot;/api/users/login&quot;) {<br>          contentType(ContentType.Application.Json)<br>          setBody(userLoginDto)<br>      }<br><br>      assertEquals(response.status, HttpStatusCode.OK)<br><br>      val res = json.decodeFromString&lt;UserWithTokenDto&gt;(response.bodyAsText())<br>      // token<br>      client = createClient {<br>          install(ContentNegotiation) {<br>              json()<br>          }<br>          install(Auth) {<br>              bearer {<br>                  loadTokens {<br>                      // Load tokens from a local storage and return them as the &#39;BearerTokens&#39; instance<br>                      BearerTokens(res.token, res.token)<br>                  }<br>              }<br>          }<br>      }<br><br>      response = client.get(&quot;/api/users/me&quot;) {<br>          contentType(ContentType.Application.Json)<br>      }<br><br>      assertEquals(response.status, HttpStatusCode.OK)<br>      val resUser = json.decodeFromString&lt;UserDto&gt;(response.bodyAsText())<br>      assertAll(<br>          { assertEquals(resUser.name, userDto.name) },<br>          { assertEquals(resUser.email, userDto.email) },<br>          { assertEquals(resUser.username, userDto.username) },<br>          { assertEquals(resUser.avatar, userDto.avatar) },<br>          { assertEquals(resUser.role, userDto.role) },<br>      )<br>  }<br>// ...<br>}</pre><h3>Deploy with Docker</h3><p>The next is to deploy or service. We will use Docker to deploy it. Docker is an open-source platform that allows developers to automate the deployment and management of applications within isolated containers. Containers are lightweight, portable, and self-sufficient environments that package all the necessary dependencies and components to run an application. Advantages of deploying a service with Docker include:</p><ul><li>Portability: Docker containers can run consistently across different environments, such as development, testing, and production, ensuring that the application behaves the same way everywhere.</li><li>Scalability: Docker enables easy scaling of services by deploying multiple containers across multiple machines, efficiently utilizing resources.</li><li>Isolation: Containers provide process-level isolation, preventing conflicts between dependencies and allowing for better resource allocation.</li><li>Versioning and Rollback: Docker images can be versioned, allowing easy rollbacks to previous versions in case of issues or bugs.</li><li>DevOps Integration: Docker integrates well with DevOps practices, facilitating continuous integration, continuous delivery (CI/CD), and infrastructure automation.</li></ul><p>Docker simplifies the deployment process, enhances application portability, and improves resource utilization, making it a popular choice for deploying and managing services.</p><p>We can use the <a href="https://ktor.io/docs/docker.html#configure-plugin">Ktor plugin</a> to create our container and configure it.</p><pre>// To generate Docker Image with JRE 17<br>ktor {<br>    docker {<br>        localImageName.set(&quot;hyperskill-reactive-api-kotlin-ktor&quot;)<br>        imageTag.set(&quot;0.0.1-preview&quot;)<br>        jreVersion.set(io.ktor.plugin.features.JreVersion.JRE_17)<br>        portMappings.set(<br>            listOf(<br>                io.ktor.plugin.features.DockerPortMapping(<br>                    8080,<br>                    8080,<br>                    io.ktor.plugin.features.DockerPortMappingProtocol.TCP<br>                ),<br>                io.ktor.plugin.features.DockerPortMapping(<br>                    8083,<br>                    8083,<br>                    io.ktor.plugin.features.DockerPortMappingProtocol.TCP<br>                )<br>            )<br>        )<br>    }<br>}</pre><p>But in this example, we have certificates and will show how to do it manually. For this purpose, we have a Dockerfile that creates a container solely to generate a fat JAR and subsequently create our container. Additionally, we can summarize this process in a Docker Compose file.</p><pre># With this file we create a Docker image that contains the application<br>FROM gradle:7-jdk17 AS build<br># We create a directory for the application and copy the build.gradle file<br>COPY --chown=gradle:gradle . /home/gradle/src<br>WORKDIR /home/gradle/src<br>RUN gradle buildFatJar --no-daemon<br><br># We create a new image with the application<br>FROM openjdk:17-jdk-slim-buster<br>EXPOSE 8080:8080<br>EXPOSE 8083:8082<br># Directory to store the application<br>RUN mkdir /app<br># Copy the certificate to the container (if it is necessary)<br>RUN mkdir /cert<br>COPY --from=build /home/gradle/src/cert/* /cert/<br># Copy the jar file to the container<br>COPY --from=build /home/gradle/src/build/libs/ktor-reactive-rest-hyperskill-all.jar /app/ktor-reactive-rest-hyperskill.jar<br># Run the application<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app/ktor-reactive-rest-hyperskill.jar&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueiFS6nNw0hYEVpJG0QuZA.png" /></figure><h3>And now, what’s next?</h3><p>I hope this series of tutorials has been interesting and has opened up options for you to develop as a developer, creating your services. But this is just the tip of the iceberg of the many things you can do. The only limit you will have is yourself, so I invite you to keep improving and coding your services.</p><p>You have the code of this project at <a href="https://github.com/joseluisgs/ktor-reactive-rest-hyperskill">https://github.com/joseluisgs/ktor-reactive-rest-hyperskill</a>. The code of this part is this link: <a href="https://github.com/joseluisgs/ktor-reactive-rest-hyperskill/releases">https://github.com/joseluisgs/ktor-reactive-rest-hyperskill/releases</a>. Please don’t forget to give a star or follow me to be aware of new tutorials and news. <strong>You can follow it commit-by-commit and use the Postman backup file to test it. </strong>Remember, this is not a code to use in a natural or production environment. It is a didactic project for you to experiment, analyze and improve or adapt to your way of programming. It is about presenting concepts and seeing how they work. If you have any questions, please do not hesitate to contact</p><p>You can continue learning and mastering spectacular things on <strong>Hyperskill</strong> through different topics and tasks that will help you improve as a developer in Kotlin technologies. The following tracks <strong>offered by JetBrains Academy on Hyperskill</strong> can be a perfect starting point. These articles show all the information and explanation of concepts and techniques. Don’t miss them!</p><ul><li><a href="https://hyperskill.org/tracks/3?category=4&amp;utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor3&amp;utm_term=27.07.2023">Kotlin Developer</a></li><li><a href="https://hyperskill.org/tracks/45?category=20&amp;utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor3&amp;utm_term=27.07.2023">Kotlin Backend Developer (Ktor)</a></li></ul><p>These tracks will provide you with hands-on experience using cutting-edge tools and teach you how to build server-side applications, ensure persistent data storage in databases, and effectively test the functionality of your applications using modern tools.</p><p>Please leave any questions or feedback in the comments section below this blog post. You can also follow us on social media platforms like <a href="https://www.reddit.com/r/Hyperskill/">Reddit</a>, <a href="https://www.linkedin.com/company/hyperskill/">LinkedIn</a>, <a href="https://twitter.com/yourhyperskill">Twitter</a>, and <a href="https://www.facebook.com/myhyperskill">Facebook</a> to stay informed about our latest articles and projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9803bca99a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hyperskill/creating-your-reactive-rest-api-with-kotlin-and-ktor-part-iii-ae9803bca99a">Creating your reactive REST API with Kotlin and Ktor part III</a> was originally published in <a href="https://medium.com/hyperskill">Hyperskill</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating your reactive REST API with Kotlin and Ktor part II]]></title>
            <link>https://medium.com/hyperskill/creating-your-reactive-rest-api-with-kotlin-and-ktor-part-ii-7b6b087f61e7?source=rss-e3e4edb52ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b6b087f61e7</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[José Luis González Sánchez]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 12:19:01 GMT</pubDate>
            <atom:updated>2023-06-07T12:19:01.289Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>We begin the second part of this tutorial on creating a reactive REST service.</p><p>In the <a href="https://medium.com/hyperskill/creating-your-reactive-rest-api-with-kotlin-and-ktor-part-i-f217be55c0bf">first part</a>, we discussed the benefits of applying reactivity in our services and created our first endpoint using Ktor.</p><p>This second part will focus on services: configure our reactive database, validate requests, and apply new techniques for error handling, storage, and real-time changes with web sockets. Finally, we will test our results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0f7cDW-SPHD23LtnVi2Bgw.png" /></figure><p>These tutorials aim to show you everything you will learn through the tracks on <a href="https://hyperskill.org/tracks?utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor&amp;utm_term=07.06.2023">Hyperskill</a>. <strong>Hyperskill is the perfect place to delve deeper, expand your knowledge, and learn more about what is presented in this tutorial. It is the ideal platform for learning Kotlin technologies and using Ktor. Feel free to join and continue your learning journey</strong>. Remember that this code is pedagogical and shows many of the contents you will learn in Hyperskill in a didactic and easy-to-read way. It is not intended to create the best production code in real environments. We know that many things can be done better, but they are exaggerated in the code so that, as a student, you can analyze the possibilities.</p><p>This part is a bit long because we created the whole structure of amazing features of our service. Take it easy and check Hyperskill for more cool features for your Kotlin and Ktor services. Please feel free to experiment and modify what can improve your self-coding with different examples and reach your goals.</p><h3>DTO and Mappers</h3><p>Our first point is to improve requests and responses. To achieve this, we will introduce an interesting pattern: <a href="https://martinfowler.com/eaaCatalog/dataTransferObject.html">DTO</a> (Data Transfer Object). DTO (Data Transfer Object) is a design pattern used for transferring data between different components or layers of an application. It encapsulates data, providing a standardized structure for communication and decoupling it from underlying data models. DTOs optimize performance by reducing the amount of data transferred and allowing fine-grained control over the exchanged information. They enhance code organization and maintainability and facilitate the evolution of data structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*5bs8hF6tXjhyX0PDsqR8yQ.gif" /><figcaption><a href="https://martinfowler.com/eaaCatalog/dataTransferObject.html">https://martinfowler.com/eaaCatalog/dataTransferObject.html</a></figcaption></figure><p>Thanks to DTOs, we can encapsulate requests and responses by mapping entities or different data types between them. For instance, imagine you have a specific date format (quite common) but store it in a different format. With DTOs, you can request the date as a string and store it in the appropriate format. Additionally, you can validate the data to ensure correctness before processing it. We may not need all the data from our “Racket” entity (or POKO, Plain Old Kotlin Object) to create or update it.</p><p>Moreover, we don’t necessarily have to send all the data either. Each request and response may require specific information. This is where DTOs provide us with more freedom in the process. Although not mandatory, depending on the problem, it is recommended to use DTOs to achieve better flexibility and control over the data exchange process. We use DTO as Serializable objects with Kotlin and not our POKO Entity.</p><pre>@Serializable<br>data class RacketRequest(<br>   val brand: String,<br>   val model: String,<br>   val price: Double,<br>   val numberTenisPlayers: Int = 0,<br>   val image: String = DEFAULT_IMAGE,<br>)<br><br><br>@Serializable<br>data class RacketResponse(<br>   val id: Long,<br>   val brand: String,<br>   val model: String,<br>   val price: Double,<br>   val numberTenisPlayers: Int,<br>   val image: String,<br>   @Serializable(with = LocalDateTimeSerializer::class)<br>   val createdAt: LocalDateTime,<br>   val updatedAt: String,<br>   val isDeleted: Boolean = false<br>)</pre><p>If we have a POKO class and several DTO classes, the next step is to use a <strong>mapper</strong> between them. We will use extension functions that map from RacketRequest to Racket and from Racket to RacketResponse in a <strong>RacketMapper</strong> file in Mappers Package.</p><pre>fun RacketRequest.toModel() = Racket(<br>   brand = this.brand,<br>   model = this.model,<br>   price = this.price,<br>   numberTenisPlayers = this.numberTenisPlayers,<br>   image = this.image<br>)<br><br>fun Racket.toResponse() = RacketResponse(<br>   id = this.id,<br>   brand = this.brand,<br>   model = this.model,<br>   price = this.price,<br>   numberTenisPlayers = this.numberTenisPlayers,<br>   image = this.image,<br>   createdAt = this.createdAt,<br>   updatedAt = this.updatedAt.toString(),<br>   isDeleted = this.isDeleted<br>)<br><br>fun List&lt;Racket&gt;.toResponse() = this.map { it.toResponse() }</pre><p>In this example, we are overengineering things a bit. Still, we gain flexibility for future expansions and the ability to adapt requests and responses to our needs. You can learn all these details in our <strong>Hyperskill</strong> tracks.</p><h3>Validations and Status Pages</h3><p>One of our fundamental problems is ensuring that the received information is correct in the problem domain or according to the information requirements. For example, it doesn’t make sense for our racket to have a negative price or for us to have an empty brand or model. We could fill our code with conditionals to ensure this task and throw exceptions, but Ktor has several plugins to help us in this mission.</p><p>To ensure the correctness of incoming information, we can utilize the <a href="https://ktor.io/docs/request-validation.html">RequestValidation</a> plugin in Ktor. This plugin allows us to validate the body of incoming requests. Whether validating a raw request body or specific properties of a request object, the RequestValidation plugin has got us covered. We can further enhance our validation capabilities if the ContentNegotiation plugin is also installed with a serializer. In case a request body fails validation, the plugin raises a RequestValidationException. We can handle this exception using the <a href="https://ktor.io/docs/status-pages.html">StatusPages plugin</a>, allowing us to gracefully handle validation errors in our application.</p><p>We add the following dependencies in our <strong>build.gradle.kts</strong> file and sync the project.</p><pre>// Content Validation<br>implementation(&quot;io.ktor:ktor-server-request-validation:$ktor_version&quot;)<br>// Server Status Pages<br>implementation(&quot;io.ktor:ktor-server-status-pages:$ktor_version&quot;)</pre><p>Now, we configure the plugins; in the Application main file, we add two new lines:</p><pre>fun Application.module() {<br>   configureSerialization() // Configure the serialization plugin<br>   configureRouting() // Configure the routing plugin<br>   configureValidation() // Configure the validation plugin<br>   configureStatusPages() // Configure the status pages plugin<br>}</pre><p>In our Plugin Package, we add the following: <strong>Validation.kt</strong></p><pre>fun Application.configureValidation() {<br>   install(RequestValidation) {<br>       racketValidation()<br>   }<br>}</pre><p>In our <strong>StatusPages.kt</strong> file:</p><pre>fun Application.configureStatusPages() {<br>   install(StatusPages) {<br>       exception&lt;RequestValidationException&gt; { call, cause -&gt;<br>           call.respond(HttpStatusCode.BadRequest, cause.reasons.joinToString())<br>       }<br>   }<br>}</pre><p>With the first plugin, we establish all the validation rules. In the second one, we define how we will respond by default for each exception that occurs in Ktor. To avoid programming all the validation rules in the same file, we will create a package called “Validations’’ and place each entity’s validation in it. Similarly, we can do the same with the Status Pages.</p><p>Let’s present the validation rules for the Racket entity. If the validation fails, it will throw a RequestValidationException, and the response will return a Bad Request (400) status code thanks to the Status Pages.</p><pre>fun RequestValidationConfig.racketValidation() {<br>   validate&lt;RacketRequest&gt; { racket -&gt;<br>       if (racket.brand.isBlank() || racket.brand.length &lt; 3) {<br>           ValidationResult.Invalid(&quot;Brand must be at least 3 characters long&quot;)<br>       } else if (racket.model.isBlank()) {<br>           ValidationResult.Invalid(&quot;Model must not be empty&quot;)<br>       } else if (racket.price &lt; 0.0) {<br>           ValidationResult.Invalid(&quot;Price must be positive value or zero&quot;)<br>       } else if (racket.numberTenisPlayers &lt; 0) {<br>           ValidationResult.Invalid(&quot;Number of tennis players must be positive number or zero&quot;)<br>       } else {<br>           // Everything is ok!<br>           ValidationResult.Valid<br>       }<br>   }<br>}</pre><p>Now we can show an example using Postman to test it. Now we can see that once the Request DTO reaches our route (endpoint) in a POST or PUT request, the Validation middleware will automatically act. If any of the specified constraints are not met, we will receive a RequestValidationException. This exception will be handled by the Status Pages system, which will retrieve the exception message and the indicated error code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*9cFmnBiEKZXLct14jzgtCg.png" /><figcaption>Validation body</figcaption></figure><p>Also, we can use this idea to generate a Bad Request response when the id parameter (for find, update, or delete) is not a valid number.</p><pre>// When we try to convert a string to a number and it fails we respond with a 400 Bad Request<br>exception&lt;NumberFormatException&gt; { call, cause -&gt;<br>   call.respond(HttpStatusCode.BadRequest, &quot;${cause.message}. The input param is not a valid number&quot;)<br>}</pre><p>And apply it in our <strong>route</strong>. If a NumberFormatException appears, it will be handled, and the Status page does its magic.</p><pre>call.parameters[&quot;id&quot;]?.toLong()?.let { id -&gt;<br>   racketsService.findById(id)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*lrOW88hgq--TZ8gbrgv8og.png" /><figcaption>Validation parameters</figcaption></figure><h3>Database Reactive Storage</h3><p>We know that having in-memory storage is tedious. Let’s implement our repository to work with a reactive database. Now this is a new alternative; what does it give us?</p><p>The main difference between <strong>JDBC</strong> (Java Database Connectivity) and <strong>R2DBC</strong> (Reactive Relational Database Connectivity) lies in their approach and functioning.</p><p><strong>JDBC</strong> is a traditionally used API in Java environments for interacting with relational databases <strong>synchronously</strong>. It follows a <strong>blocking</strong> approach, meaning <strong>each database operation blocks the execution thread until it completes</strong>. It can result in limited scalability, especially in applications that require high performance and concurrency.</p><p>On the other hand, <strong>R2DBC</strong> is a reactive API designed for <strong>asynchronous</strong> and <strong>reactive</strong> interaction with relational databases. It allows <strong>non-blocking</strong> database operations, meaning <strong>the main execution thread is not blocked. Instead, it uses notifications and callbacks to handle events efficiently</strong>. This enables better scalability and improved performance in applications that require high responsiveness and handling of multiple concurrent requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMAwbU5H8dRUmTejDC7bAw.png" /><figcaption>Reactive Database Approach by O’Reilly <a href="https://www.oreilly.com/content/wp-content/uploads/sites/2/2019/06/rmsa_0207-30c0306d4e47f1d4549937a30c2edb03.png">What is a Reactive Microservice</a></figcaption></figure><p>Remember, the choice between JDBC and R2DBC depends on the specific requirements of the application and the preference for a synchronous or reactive approach. JDBC is a synchronous API that blocks execution threads, while R2DBC is a reactive API that enables non-blocking operations and more efficient handling of concurrent requests. But this is a full reactive API, so we select a reactive database approach. We can learn more about this question or specific alternative in <a href="https://hyperskill.org/tracks?utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor&amp;utm_term=07.06.2023"><strong>Hyperskill’s</strong></a> tracks.</p><p>The first step is to select a library to help us to code with a reactive database. We will use <a href="https://ufoss.org/kotysa/kotysa.html">Kotysa</a>. Kotysa is a light ORM that offers the idiomatic way to write Kotlin type-safe SQL for Kotlin using JDBC or R2DBC approach. In Reactive mode, it provides a SQL client API using suspend functions and Flow from kotlinx.coroutines. We will use it as a Relational Database. We will use H2 because we can use it like a memory database for this development process.</p><p>Again, we add the following dependencies in our <strong>build.gradle.kts</strong> file and sync the project.</p><pre>implementation(&quot;org.ufoss.kotysa:kotysa-r2dbc:$kotysa_version&quot;)<br>implementation(&quot;io.r2dbc:r2dbc-h2:$h2_r2dbc_version&quot;)</pre><h4>Configure the app</h4><p>Our first step is to configure our application for database usage. To do this, we will add options to our application.conf file to connect to our database, such as the connection URL, username, and password. We include a special key to init the data en in dev mode.</p><pre>database {<br>   driver = &quot;h2&quot;<br>   protocol =&quot;mem&quot;<br>   user = &quot;sa&quot;<br>   user = ${?DATABASE_USER}<br>   password = &quot;&quot;<br>   password = ${?DATABASE_PASSWORD}<br>   database = &quot;r2dbc:h2:mem:///rackets;DB_CLOSE_DELAY=-1&quot;<br>   database = ${?DATABASE_NAME}<br>   ## Init database data<br>   initDatabaseData = true<br>}</pre><h4>Defining Tables and Entities</h4><p>The next step is to define our table structure and the row entity to map the data. We can use our original POKO racket model. Again, this is optional but recommended. Like DTOs, this allows us to map data between our POKO model and our Entity in case of data incompatibilities. We have chosen this approach because we don’t want null values in the ID field, but Kotysa requires them to determine whether it should generate an auto-incrementing key. This<a href="https://github.com/ufoss-org/kotysa/issues/136#issuecomment-1561391983"> behavior might change in future versions</a>. In a new Package called Entities, we code the Racket Table and Racket Entity</p><pre>bject RacketTable : H2Table&lt;RacketEntity&gt;() {<br>   // Autoincrement and primary key<br>   val id = autoIncrementBigInt(RacketEntity::id).primaryKey()<br>   // Other fields<br>   val brand = varchar(RacketEntity::brand)<br>   val model = varchar(RacketEntity::model)<br>   val price = doublePrecision(RacketEntity::price)<br>   val numberTenisPlayers = integer(RacketEntity::numberTenisPlayers, &quot;number_tenis_players&quot;)<br>   val image = varchar(RacketEntity::image, &quot;image&quot;)<br>   // metadata<br>   val createdAt = timestamp(RacketEntity::createdAt, &quot;created_at&quot;)<br>   val updatedAt = timestamp(RacketEntity::updatedAt, &quot;updated_at&quot;)<br>   val isDeleted = boolean(RacketEntity::isDeleted, &quot;is_deleted&quot;)<br>}<br><br>data class RacketEntity(<br>   val id: Long?,<br>   val brand: String,<br>   val model: String,<br>   val price: Double,<br>   val numberTenisPlayers: Int = 0,<br>   val image: String = DEFAULT_IMAGE,<br>   val createdAt: LocalDateTime = LocalDateTime.now(),<br>   val updatedAt: LocalDateTime = LocalDateTime.now(),<br>   val isDeleted: Boolean = false<br>)</pre><p>And we add the following methods to our Racket Mapper.</p><pre>fun RacketEntity.toModel() = Racket(<br>   id = this.id ?: Racket.NEW_RACKET,<br>   brand = this.brand,<br>   model = this.model,<br>   price = this.price,<br>   numberTenisPlayers = this.numberTenisPlayers,<br>   image = this.image,<br>   createdAt = this.createdAt,<br>   updatedAt = this.updatedAt,<br>   isDeleted = this.isDeleted<br>)<br><br>fun List&lt;RacketEntity&gt;.toModel() = this.map { it.toModel() }<br><br>fun Racket.toEntity() = RacketEntity(<br>   id = if (this.id == Racket.NEW_RACKET) null else this.id,<br>   brand = this.brand,<br>   model = this.model,<br>   price = this.price,<br>   numberTenisPlayers = this.numberTenisPlayers,<br>   image = this.image,<br>   createdAt = this.createdAt,<br>   updatedAt = this.updatedAt,<br>   isDeleted = this.isDeleted<br>)</pre><h4>Coding the Database Service Client</h4><p>In this initial version, we will create a Customer Service Database that is in charge of creating said client, creating the tables, and starting the data. You can find it in the Package: Services -&gt; Database. This client will load the configuration and database parameters of our application.conf file, we inject the dependence in the constructor.</p><pre>class DataBaseService(<br>   private val dataBaseConfig: ApplicationConfig = ApplicationConfig(&quot;application.conf&quot;)<br>) {<br><br>   private val connectionFactory by lazy {<br>       val options = ConnectionFactoryOptions.builder()<br>           .option(ConnectionFactoryOptions.DRIVER, dataBaseConfig.property(&quot;database.driver&quot;).getString())<br>           .option(ConnectionFactoryOptions.PROTOCOL, dataBaseConfig.property(&quot;database.protocol&quot;).getString())<br>           .option(ConnectionFactoryOptions.USER, dataBaseConfig.property(&quot;database.user&quot;).getString())<br>           .option(ConnectionFactoryOptions.PASSWORD, dataBaseConfig.property(&quot;database.password&quot;).getString())<br>           .option(ConnectionFactoryOptions.DATABASE, dataBaseConfig.property(&quot;database.database&quot;).getString())<br>           .build()<br>       ConnectionFactories.get(options)<br>   }<br><br>   private val initDatabaseData by lazy {<br>       dataBaseConfig.propertyOrNull(&quot;database.initDatabaseData&quot;)?.getString()?.toBoolean() ?: false<br>   }<br><br>   // Our client<br>   val client = connectionFactory.coSqlClient(getTables())<br><br>   init {<br>       logger.debug { &quot;Init DataBaseService&quot; }<br>       initDatabase()<br>   }<br><br>   // Our tables<br>   private fun getTables(): H2Tables {<br>       // Return tables<br>       return tables().h2(RacketTable)<br>   }<br><br>   fun initDatabase() = runBlocking {<br>       logger.debug { &quot;Init DatabaseService&quot; }<br>       createTables()<br>       // Init data<br>       if (initDatabaseData) {<br>           initDataBaseDataDemo()<br>       }<br>   }<br><br><br>   // demo data<br>   suspend fun initDataBaseDataDemo() {<br>       clearDataBaseData()<br>       initDataBaseData()<br>   }<br><br>   // Create tables if not exists<br>   private suspend fun createTables() = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;Creating the tables...&quot; }<br>       launch {<br>           client createTableIfNotExists RacketTable<br>       }<br>   }<br><br>   // Clear all data<br>   private suspend fun clearDataBaseData() = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;Deleting data...&quot; }<br>       launch {<br>           client deleteAllFrom RacketTable<br>       }<br>   }<br><br>   // Init data<br>   private suspend fun initDataBaseData() = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;Saving rackets demo data...&quot; }<br>       launch {<br>           racketsDemoData().forEach {<br>               client insert it.value.copy(id = Racket.NEW_RACKET).toEntity()<br>           }<br>       }<br>   }<br>}</pre><h4>Updating the repository to use our Database storage</h4><p>Finally, we updated our racket repository to use the database storage system. We inject our database dependence in the constructor.</p><pre>class RacketsRepositoryImpl(<br>   private val dataBaseService: DataBaseService<br>) : RacketsRepository {<br><br>   override suspend fun findAll(): Flow&lt;Racket&gt; = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;findAll&quot; }<br>       return@withContext (dataBaseService.client selectFrom RacketTable)<br>           .fetchAll().map { it.toModel() }<br>   }<br><br>   override suspend fun findById(id: Long): Racket? = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;findById: $id&quot; }<br>       return@withContext (dataBaseService.client selectFrom RacketTable<br>               where RacketTable.id eq id)<br>           .fetchFirstOrNull()?.toModel()<br>   }<br><br>   override suspend fun findAllPageable(page: Int, perPage: Int): Flow&lt;Racket&gt; = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;findAllPageable: $page, $perPage&quot; }<br>       val myLimit = if (perPage &gt; 100) 100L else perPage.toLong()<br>       val myOffset = (page * perPage).toLong()<br>       return@withContext (dataBaseService.client selectFrom RacketTable<br>               limit myLimit offset myOffset)<br>           .fetchAll().map { it.toModel() }<br>   }<br><br>   override suspend fun findByBrand(brand: String): Flow&lt;Racket&gt; = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;findByBrand: $brand&quot; }<br>       return@withContext (dataBaseService.client selectFrom RacketTable)<br>           .fetchAll()<br>           .filter { it.brand.contains(brand, true) }<br>           .map { it.toModel() }<br>   }<br><br>   override suspend fun save(entity: Racket): Racket = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;save: $entity&quot; }<br>       if (entity.id == Racket.NEW_RACKET) {<br>           create(entity)<br>       } else {<br>           update(entity)<br>       }<br>   }<br><br>   private suspend fun create(entity: Racket): Racket {<br>       val newEntity = entity.copy(createdAt = LocalDateTime.now(), updatedAt = LocalDateTime.now())<br>           .toEntity()<br>       logger.debug { &quot;create: $newEntity&quot; }<br>       return (dataBaseService.client insertAndReturn newEntity).toModel()<br>   }<br><br>   private suspend fun update(entity: Racket): Racket {<br>       logger.debug { &quot;update: $entity&quot; }<br>       val updateEntity = entity.copy(updatedAt = LocalDateTime.now()).toEntity()<br>       (dataBaseService.client update RacketTable<br>               set RacketTable.brand eq updateEntity.brand<br>               set RacketTable.model eq updateEntity.model<br>               set RacketTable.price eq updateEntity.price<br>               set RacketTable.numberTenisPlayers eq updateEntity.numberTenisPlayers<br>               set RacketTable.image eq updateEntity.image<br>               where RacketTable.id eq entity.id)<br>           .execute()<br>       return updateEntity.toModel()<br>   }<br><br>   override suspend fun delete(entity: Racket): Racket {<br>       logger.debug { &quot;delete: $entity&quot; }<br>       (dataBaseService.client deleteFrom RacketTable<br>               where RacketTable.id eq entity.id)<br>           .execute()<br>       return entity<br>   }<br><br>   override suspend fun deleteAll() {<br>       logger.debug { &quot;deleteAll&quot; }<br>       dataBaseService.client deleteAllFrom RacketTable<br>   }<br><br>   override suspend fun saveAll(entities: Iterable&lt;Racket&gt;): Flow&lt;Racket&gt; {<br>       logger.debug { &quot;saveAll: $entities&quot; }<br>       entities.forEach { save(it) }<br>       return this.findAll()<br>   }<br>}</pre><h3>Coding our services.</h3><p>The next step is enriching the API service, so we encapsulate our repository as a service that includes different functionalities besides saving info in a database.</p><h4>Cache</h4><p>The cache system is recommended for servers for the following reasons:</p><ul><li>It improves overall performance by storing frequently accessed data closer to the processor, reducing latency.</li><li>It helps to reduce the load on the server’s main memory, allowing faster access to critical data.</li><li>Caching minimizes network traffic by serving content directly from the cache, reducing the need for repeated data requests.</li><li>It enhances scalability by efficiently handling increased user requests and optimizing server resources.</li></ul><p>We use a reactive cache, <a href="https://reactivecircus.github.io/cache4k/">Cache4k</a>, to add it to our <strong>build.gradle.kts</strong> file and sync the project:</p><pre>// Cache 4K for in-memory cache<br>implementation(&quot;io.github.reactivecircus.cache4k:cache4k:$cache_version&quot;)</pre><p>To use our cache service, we will create CacheService with parameters obtained from application.conf. In our <strong>RacketServiceImpl</strong>, the algorithm to use our cache: If we request a racket, we search for it in the cache, and only if it doesn’t exist, we obtain it in the database (we subsequently add it to the cache for future searches), if it doesn’t exist we return an error. We update the cache with the new data if we add or modify a racket. And if we delete a racket, we invalidate it in the cache.</p><p>Here is a prototype of findById, but we need to add more things ;)</p><pre>verride suspend fun findById(id: Long): Racket {<br>   logger.debug { &quot;findById: search racket by id&quot; }<br>   // find in cache if not found find in repository<br>   return cacheService.rackets.get(id)?.let {<br>       logger.debug { &quot;findById: found in cache&quot; }<br>       it<br>   } ?: run {<br>       racketsRepository.findById(id)?.let { racket -&gt;<br>           logger.debug { &quot;findById: found in repository&quot; }<br>           cacheService.rackets.put(id, racket)<br>           racket<br>       } ?: throw RuntimeException(&quot;Racket not found&quot;)<br>   }<br>}</pre><h4>Railway Oriented Programming</h4><p><a href="https://fsharpforfunandprofit.com/rop/">Railway Oriented Programming (ROP)</a> is a functional programming concept for handling errors and composing sequential operations. It organizes operations into a sequence of steps, where each step either succeeds and continues to the next step to reach the happy path or fails and branches to an error-handling path. The advantages of ROP:</p><ul><li>Improved error handling: ROP provides a structured approach to handling errors, making tracking and predicting failures easier.</li><li>Composability: ROP allows the composition of multiple operations into a single sequence, making it easier to reason about and maintain code.</li><li>Separation of concerns: ROP encourages separating business logic from error-handling code, leading to cleaner and more maintainable code. ROP provides a structured approach to handling errors and allows for explicit branching based on success or failure. In contrast, exceptions can handle exceptional cases or unexpected errors.</li><li>Testability: ROP facilitates unit testing by allowing each step to be tested individually and enabling easier mocking or stubbing of dependencies.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*5hiy7XMNfKOjhvdhoVJfeA.png" /><figcaption>ROP: <a href="https://fsharpforfunandprofit.com/rop/">https://fsharpforfunandprofit.com/rop/</a></figcaption></figure><p>To use this programming technique, we add the following lines to our <strong>gradle.build.kts </strong>and sync the project to use the <a href="https://github.com/michaelbull/kotlin-result">kotlin-result</a> library:</p><pre>// Result for error handling Railway Oriented Programming<br>implementation(&quot;com.michael-bull.kotlin-result:kotlin-result:$result_version&quot;)</pre><p>We create the Errors structure for Racket’s operation.</p><pre>sealed class RacketError(val message: String) {<br>   class NotFound(message: String) : RacketError(message)<br>   class BadRequest(message: String) : RacketError(message)<br>}</pre><p>Now we can use it in our service and route. For example, we have an example to find a racket with our service:</p><pre>override suspend fun findById(id: Long): Result&lt;Racket, RacketError&gt; {<br>   logger.debug { &quot;findById: search racket by id&quot; }<br>   // find in cache if not found find in repository<br>   return cacheService.rackets.get(id)?.let {<br>       logger.debug { &quot;findById: found in cache&quot; }<br>       Ok(it)<br>   } ?: run {<br>       racketsRepository.findById(id)?.let { racket -&gt;<br>           logger.debug { &quot;findById: found in repository&quot; }<br>           cacheService.rackets.put(id, racket)<br>           Ok(racket)<br>       } ?: Err(RacketError.NotFound(&quot;Racket with id $id not found&quot;))<br>   }<br>}</pre><p>And how to search for a racket by an id in our <strong>route</strong>.</p><pre>// Get one racket by id --&gt; GET /api/rackets/{id}<br>get(&quot;{id}&quot;) {<br>   logger.debug { &quot;GET BY ID /$ENDPOINT/{id}&quot; }<br>   call.parameters[&quot;id&quot;]?.toLong()?.let { id -&gt;<br>       racketsService.findById(id).mapBoth(<br>           success = { call.respond(HttpStatusCode.OK, it.toResponse()) },<br>           failure = { handleRacketErrors(it) }<br>       )<br>   }<br>}</pre><p>We use the <em>mapBoth</em> to separate the happy result from the error. We can handle all the errors thanks to an extension function handleRacketErrors, where we pass the error, and at this point, we perform the correct response from each type of error. So our code is spotless compared to the first version.</p><pre>private suspend fun PipelineContext&lt;Unit, ApplicationCall&gt;.handleRacketErrors(<br>   error: RacketError,<br>) {<br>   // We can handle the errors in a different way<br>   when (error) {<br>       // Racket Errors<br>       is RacketError.NotFound -&gt; call.respond(HttpStatusCode.NotFound, error.message)<br>       is RacketError.BadRequest -&gt; call.respond(HttpStatusCode.BadRequest, error.message)<br>   }<br>}</pre><h4>Real-time notifications with WebSockets</h4><p><a href="https://en.wikipedia.org/wiki/WebSocket">WebSocket</a> is a communication protocol that provides full-duplex communication between a client and a server over a single, long-lived connection. It enables real-time, bi-directional communication between the two endpoints. We can use WebSocket when:</p><ul><li>Real-time data is required: WebSocket is suitable for applications that need instant updates or frequent data exchange between the client and server.</li><li>Interactive applications: It is ideal for applications that involve real-time collaboration, chat systems, gaming, or any scenario where instant communication is vital.</li><li>Reduced latency: WebSocket eliminates the need for continuous polling or frequent requests, reducing network overhead and improving responsiveness.</li><li>Efficient resource utilization: It allows for simultaneous, persistent connections, reducing the overhead of establishing new connections for each interaction and enabling efficient resource utilization on the server.</li></ul><p>So we perform our notification system when we add, update or delete a racket. We can use the <a href="https://refactoring.guru/design-patterns/observer">Observer pattern</a> (look at the repository’s commits), but in this case, we use a Reactive State using the <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-state-flow/"><strong>StateFlow</strong></a> or <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/"><strong>SharedFow</strong></a> Kotlin Coroutines. The Observer pattern is useful for real-time notifications to a list of subscribers, while StateFlow in Kotlin provides reactive data flow with automatic notification of relevant changes. Observer suits smaller subscriber lists and infrequent changes, whereas StateFlow is ideal for leveraging Kotlin’s reactive capabilities and handling larger-scale data flows. The choice depends on the system’s complexity, the subscriber list size, change frequency, and required responsiveness. Consider your specific needs when selecting the appropriate approach.</p><p>So, we create a <strong>Notification Dto</strong>, and in our <strong>racket service</strong>, we create the reactive state and a function to modify it.</p><pre>/ Real Time Notifications and WebSockets<br>// We can notify use a reactive system with StateFlow<br>private val _notificationState: MutableStateFlow&lt;RacketNotification&gt; = MutableStateFlow(<br>   RacketNotification(<br>       entity = &quot;&quot;,<br>       type = NotificationType.OTHER,<br>       id = null,<br>       data = null<br>   )<br>)<br>override val notificationState: StateFlow&lt;RacketNotification&gt; = _notificationState<br><br>private suspend fun onChange(type: NotificationType, id: Long, data: Racket) {<br>   logger.debug { &quot;onChange: Notification on Rackets: $type, notification updates to subscribers: $data&quot; }<br>   // update notification state<br>   _notificationState.value = RacketNotification(<br>       entity = &quot;RACKET&quot;,<br>       type = type,<br>       id = id,<br>       data = data.toResponse()<br>   )<br>}</pre><p>For example, if we delete a new racket in our service, we can update the state:</p><pre>override suspend fun delete(id: Long): Result&lt;Racket, RacketError&gt; {<br>   logger.debug { &quot;delete: delete racket&quot; }<br>   // find, if exists delete in cache and repository and notify<br>   return findById(id).andThen {<br>       Ok(racketsRepository.delete(it).also { res -&gt;<br>           cacheService.rackets.invalidate(id)<br>           onChange(NotificationType.DELETE, id, res)<br>       })<br>   }<br>}</pre><p>But, we need to interact as a web service in our route. We include the dependence in our <strong>build.gradle.kts</strong> file and sync the project.</p><pre>// WebSockets<br>implementation(&quot;io.ktor:ktor-server-websockets:$ktor_version&quot;)</pre><p>We configured the WebSocket Plugin (Plugins Package), and we need to add the configuration to <strong>Application.module</strong> like other plugins.</p><p>We create a route for our WebSocket in our route and react to the change of the Notification State consuming the<strong> </strong>StateFlow or SharedFlow.</p><pre>// WebSockets Real Time Updates and Notifications<br>webSocket(&quot;/$ENDPOINT/notifications&quot;) {<br>   sendSerialized(&quot;Notifications WS: Rackets - Rackets API&quot;)<br>   val initTime = LocalDateTime.now()<br>   // Remember it will autoclose the connection, see config<br>   // Now we can listen and react to the changes in the StateFlow<br>   racketsService.notificationState<br>       // Sometimes we need to do something when we start<br>       .onStart {<br>           logger.debug { &quot;notificationState: onStart to ${this.hashCode()}&quot; }<br>           // Sometimes we need to filter any values<br>       }.filter {<br>           // we filter the values: we only send the ones that are not empty and are after the init time<br>           it.entity.isNotEmpty() &amp;&amp; it.createdAt.isAfter(initTime)<br>           // we collect the values and send them to the client<br>       }.collect {<br>           logger.debug { &quot;notificationState: collect $it and sent to ${this.hashCode()}&quot; }<br>           sendSerialized(it) // WS function to send the message to the client<br>       }<br>}</pre><p>Now we can test it in Postman, thanks to <a href="https://learning.postman.com/docs/sending-requests/websocket/websocket/">WebSocket</a> functionality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERmB1f8F4ReCHYRudcM74g.png" /></figure><h4>Storage files</h4><p>The next stage is to create a storage service to upload files, for example, the image of each racket. In application.conf we use a special key value to indicate the upload directory to save the files.</p><p>So we will code in this <strong>service</strong> two methods, one to save an image and another to retrieve it. We also create Error and use Result (ROP):</p><pre>override suspend fun saveFile(<br>   fileName: String,<br>   fileUrl: String,<br>   fileBytes: ByteArray<br>): Result&lt;Map&lt;String, String&gt;, StorageError&gt; =<br>   withContext(Dispatchers.IO) {<br>       logger.debug { &quot;Saving file in: $fileName&quot; }<br>       return@withContext try {<br>           File(&quot;${uploadDir}/$fileName&quot;).writeBytes(fileBytes)<br>           Ok(<br>               mapOf(<br>                   &quot;fileName&quot; to fileName,<br>                   &quot;createdAt&quot; to LocalDateTime.now().toString(),<br>                   &quot;size&quot; to fileBytes.size.toString(),<br>                   &quot;url&quot; to fileUrl,<br>               )<br>           )<br>       } catch (e: Exception) {<br>           Err(StorageError.BadRequest(&quot;Error saving file: $fileName&quot;))<br>       }<br>   }<br><br>override suspend fun getFile(fileName: String): Result&lt;File, StorageError&gt; = withContext(Dispatchers.IO) {<br>   logger.debug { &quot;Get file: $fileName&quot; }<br>   return@withContext if (!File(&quot;${uploadDir}/$fileName&quot;).exists()) {<br>       Err(StorageError.NotFound(&quot;File Not Found in storage: $fileName&quot;))<br>   } else {<br>       Ok(File(&quot;${uploadDir}/$fileName&quot;))<br>   }<br>}</pre><p>So, in our route we can use a patch petition to update the racket image using <a href="https://ktor.io/docs/requests.html#form_data">multipart</a> request:</p><pre>// Update a racket image --&gt; PATCH /api/rackets/{id}<br>patch(&quot;{id}&quot;) {<br>   logger.debug { &quot;PATCH /$ENDPOINT/{id}&quot; }<br><br>   call.parameters[&quot;id&quot;]?.toLong()?.let { id -&gt;<br>       val baseUrl =<br>           call.request.origin.scheme + &quot;://&quot; + call.request.host() + &quot;:&quot; + call.request.port() + &quot;/$ENDPOINT/image/&quot;<br>       val multipartData = call.receiveMultipart()<br>       multipartData.forEachPart { part -&gt;<br>           if (part is PartData.FileItem) {<br>               val fileName = part.originalFileName as String<br>               val fileBytes = part.streamProvider().readBytes()<br>               val fileExtension = fileName.substringAfterLast(&quot;.&quot;)<br>               val newFileName = &quot;${System.currentTimeMillis()}.$fileExtension&quot;<br>               val newFileUrl = &quot;$baseUrl$newFileName&quot;<br>               // Save the file<br>               storageService.saveFile(newFileName, newFileUrl, fileBytes).andThen {<br>                   // Update the racket Image<br>                   racketsService.updateImage(<br>                       id = id,<br>                       image = newFileUrl<br>                   )<br>               }.mapBoth(<br>                   success = { call.respond(HttpStatusCode.OK, it.toResponse()) },<br>                   failure = { handleRacketErrors(it) }<br>               )<br>           }<br>           part.dispose()<br>       }<br>   }<br>}</pre><p>Now we can test with Postman to send a file and update a racket or get this file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*v6xtIm1wPmsKIkBxd8Cn6g.png" /><figcaption>Update an Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*bbFhSmT59EHQ30bpqg9wwQ.png" /><figcaption>Getting a racket image</figcaption></figure><h4>Our Final Route</h4><p>Finally, we have our route that calls the services we will use. We emphasize the ROP approach and how we handle all errors by creating clean and readable code that concatenates options based on the happy path or uses web sockets with a reactive state to perform a real-time notification system.</p><h3>Testing</h3><h4>Testing the racket repository</h4><p>We are now entering a crucial and essential part: testing our code. To do this, we will make use of <a href="https://junit.org/junit5/">JUnit</a>. JUnit is a widely used open-source testing framework for Java applications. It provides a simple and convenient way to write and execute unit tests for individual units of code, such as methods or classes. JUnit offers various annotations, assertions, and test runners to facilitate the creation and execution of tests. We will extend the configuration to use a special library to test suspended functions. We add the following dependencies in our <strong>build.gradle.kts</strong> file and sync the project.</p><pre>// Testing<br>testImplementation(&quot;io.ktor:ktor-server-tests-jvm:$ktor_version&quot;)<br>// testImplementation(&quot;org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version&quot;)<br>// JUnit 5 instead of JUnit 4<br>testImplementation(&quot;org.junit.jupiter:junit-jupiter-api:$junit_version&quot;)<br>testImplementation(&quot;org.junit.jupiter:junit-jupiter-engine:$junit_version&quot;)<br>// To test coroutines and suspend functions<br>testImplementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_test_version&quot;)</pre><p>In this initial stage, they are not the best tests of a repository, but they are illustrative for what we want. We can see the use of assertions to check the indicated CRUD operations. So in the test folder, you can find the test files.</p><pre>class RacketsRepositoryImplTest {<br>   val dataBaseService = DataBaseService(ApplicationConfig(&quot;application.conf&quot;))<br>   val repository = RacketsRepositoryImpl(dataBaseService)<br><br>   @BeforeEach<br>   fun setUp() = runTest {<br>       // Clean and restore database with data<br>       dataBaseService.initDataBaseDataDemo()<br>   }<br><br>   @Test<br>   fun findAll() = runTest {<br>       val rackets = repository.findAll().toList()<br>       assertAll(<br>           { assertEquals(4, rackets.size) },<br>           { assertEquals(&quot;Babolat&quot;, rackets[0].brand) },<br>           { assertEquals(&quot;Babolat&quot;, rackets[1].brand) },<br>           { assertEquals(&quot;Head&quot;, rackets[2].brand) },<br>           { assertEquals(&quot;Wilson&quot;, rackets[3].brand) }<br>       )<br>   }<br><br>   @Test<br>   suspend fun findById() = runTest {<br>       val racket = repository.findById(1)!!<br>       assertAll(<br>           { assertEquals(1, racket.id) },<br>           { assertEquals(&quot;Babolat&quot;, racket.brand) }<br>       )<br>   }<br><br>   @Test<br>   fun findByIdNotFound() = runTest {<br>       val racket = repository.findById(-100)<br>       assertNull(racket)<br>   }<br><br>   // . . .<br><br>   @Test<br>   fun saveNewRacket() = runTest {<br>       val racket = Racket(brand = &quot;Test Brand&quot;, model = &quot;Test Model&quot;, price = 100.0)<br>       val newRacket = repository.save(racket)<br>       assertAll(<br>           { assertEquals(&quot;Test Brand&quot;, newRacket.brand) },<br>           { assertEquals(&quot;Test Model&quot;, newRacket.model) },<br>           { assertEquals(100.0, newRacket.price) }<br>       )<br>   }<br><br>   // . . .<br>   <br>   @Test<br>   fun delete() = runTest {<br>       // Save a new racket<br>       val racket = Racket(brand = &quot;Test Brand&quot;, model = &quot;Test Model&quot;, price = 100.0)<br>       val newRacket = repository.save(racket)<br>       val deleted = repository.delete(newRacket)<br>       val exists = repository.findById(newRaquet.id)<br>       assertAll(<br>           { assertEquals(&quot;Test Brand&quot;, deleted.brand) },<br>           { assertEquals(&quot;Test Model&quot;, deleted.model) },<br>           { assertEquals(100.0, deleted.price) },<br>           { assertNull(exists) }<br>       )<br>   }<br>}</pre><p>Running our tests, we obtain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*0o9PKNEVzIXTB8eUHc_wPw.png" /><figcaption>Testing repository</figcaption></figure><h4>Testing the racket service</h4><p>For testing our service, we test with doubles so that we will use mocks. Testing with mocks involves creating mock objects that mimic the behavior of real dependencies. These mock objects are programmed to respond to method calls and allow expectations to be set on their interactions. Using mocks, developers can isolate the code being tested, control the behavior of dependencies, simulate various scenarios, and verify interactions with the tested code.</p><p>We will use the <a href="https://mockk.io/">MockK</a> library, so we must add the following library to a sour project in the build.gradle.kts file and resync our project</p><pre>// MockK to test with mocks<br>testImplementation(&quot;io.mockk:mockk:$mockk_version&quot;)</pre><p>We create the class to test the service methods. We extended the class with @ExtendWith(MockKExtension::class) to perform tests with JUnit and create the mocks with @MockK annotation and @InjectMockK to inject the mock as a dependency of the class for testing.</p><p>So, we create each test where we simulate the mock behavior to respond to method calls and allow expectations to test the service methods with JUnit. We can verify the number of calls to a dependency.</p><p>Here is an example</p><pre>@ExtendWith(MockKExtension::class)<br>class RacketsServiceImplTest {<br><br>   @MockK<br>   lateinit var repository: RacketsRepositoryImpl<br>   @MockK<br>   lateinit var cache: CacheService<br>   @InjectMockKs<br>   lateinit var service: RacketsServiceImpl<br><br>   val rackets = racketsDemoData().values<br><br>   @Test<br>   fun findAll() = runTest {<br>       // Given<br>       coEvery { repository.findAll() } returns flowOf(rackets.first())<br>       // When<br>       val result = service.findAll().toList()<br>       // Then<br>       assertAll(<br>           { assertNotNull(result) },<br>           { assertEquals(1, result.size) },<br>           { assertEquals(rackets.first(), result.first()) }<br>       )<br>       // Verifications<br>       coVerify(exactly = 1) { repository.findAll() }<br>   }<br><br>  // ...<br><br>   @Test<br>   fun save() = runTest {<br>       // Given<br>       coEvery { repository.save(any()) } returns rackets.first()<br>       coEvery { cache.rackets.put(any(), rackets.first()) } just runs // returns Unit<br>       // When<br>       val result = service.save(rackets.first())<br>       // Then<br>       assertAll(<br>           { assertNotNull(result) },<br>           { assertEquals(rackets.first(), result.get()) }<br>       )<br>       // Verifications<br>       coVerify { repository.save(any()) }<br>       coVerify { cache.rackets.put(any(), rackets.first()) }<br>   }<br><br>  // ...<br><br>   @Test<br>   fun delete() = runTest {<br>       // Given<br>       coEvery { cache.rackets.get(any()) } returns null<br>       coEvery { repository.findById(any()) } returns rackets.first()<br>       coEvery { cache.rackets.put(any(), rackets.first()) } just runs<br>       coEvery { repository.delete(any()) } returns rackets.first()<br>       coEvery { cache.rackets.invalidate(any()) } returns Unit<br>       // When<br>       val result = service.delete(1)<br>       // Then<br>       assertAll(<br>           { assertNotNull(result) },<br>           { assertEquals(rackets.first(), result.get()) }<br>       )<br>       // Verifications<br>       coVerify { cache.rackets.get(any()) }<br>       coVerify { repository.findById(any()) }<br>       coVerify { cache.rackets.put(any(), rackets.first()) }<br>       coVerify { repository.delete(any()) }<br>       coVerify { cache.rackets.invalidate(any()) }<br>   }<br>  <br>   // ...<br>}</pre><p>Running our tests, we obtain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*Kf9JSpbxgEF5a8YbopBWXg.png" /><figcaption>Testing service</figcaption></figure><h3>What ‘s next?</h3><p>You can test with Postman, and why not, try our validation process. You can follow the messages or the logger to understand the sequence or the methods.</p><p>We have continued our tutorials to be able to code our reactive REST API, gradually understanding each of its components. But we still have a lot to do in the final tutorial. Please don’t stop following the rest of the <a href="https://medium.com/hyperskill">Hyperskill Medium</a> publications, where we will see more details of what you can learn in our tracks. We will code this example:</p><ul><li>Using Koin to inject our dependencies.</li><li>Security connections with SSL</li><li>Authentication and Authorization with JWT</li><li>Test our endpoints.</li><li>Document our Service with Swagger and OpenAPI</li><li>Deploy with Docker</li></ul><p>You have the code of this project in <a href="https://github.com/joseluisgs/ktor-reactive-rest-hyperskill">https://github.com/joseluisgs/ktor-reactive-rest-hyperskill</a>. The code of this part is this link: <a href="https://github.com/joseluisgs/ktor-reactive-rest-hyperskill/releases">https://github.com/joseluisgs/ktor-reactive-rest-hyperskill/releases</a>. Please don’t forget to give a star or follow me to be aware of new tutorials and news. <strong>You can follow it commit-by-commit and use the Postman backup file to test it. </strong>Remember, this is not a code to use in a real environment or production environment. It is a didactic project for you to experiment, analyze and improve or adapt to your way of programming. It is about presenting concepts and seeing how they work. Any suggestions or proposals you can make an issue or pull request.</p><p>However, we still have many sections to cover and content for you to delve into and reinforce on <a href="https://hyperskill.org/tracks?utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor&amp;utm_term=07.06.2023"><strong>Hyperskill</strong></a> through different topics and tasks that will help you improve as a developer in Kotlin technologies. The following tracks <strong>offered by JetBrains Academy on Hyperskill</strong> can be a perfect starting point. All the information and explanation of concepts and techniques are shown in these articles. Don’t miss them!</p><ul><li><a href="https://hyperskill.org/tracks/3?category=4&amp;utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor&amp;utm_term=07.06.2023">Kotlin Developer</a></li><li><a href="https://hyperskill.org/tracks/45?category=20&amp;utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor&amp;utm_term=07.06.2023">Kotlin Backend Developer (Ktor)</a></li></ul><p>These tracks will provide you with hands-on experience using cutting-edge tools and teach you how to build server-side applications, ensure persistent data storage in databases, and effectively test the functionality of your applications using modern tools.</p><p>We encourage you to leave any questions or feedback in the comments section below this blog post. Additionally, you can follow us on social media platforms such as <a href="https://www.reddit.com/r/Hyperskill/">Reddit</a>, <a href="https://www.linkedin.com/company/hyperskill/">LinkedIn</a>, <a href="https://twitter.com/yourhyperskill">Twitter</a>, and <a href="https://www.facebook.com/myhyperskill">Facebook</a> to stay informed about our latest articles and projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b6b087f61e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hyperskill/creating-your-reactive-rest-api-with-kotlin-and-ktor-part-ii-7b6b087f61e7">Creating your reactive REST API with Kotlin and Ktor part II</a> was originally published in <a href="https://medium.com/hyperskill">Hyperskill</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating your reactive REST API with Kotlin and Ktor part I]]></title>
            <link>https://medium.com/hyperskill/creating-your-reactive-rest-api-with-kotlin-and-ktor-part-i-f217be55c0bf?source=rss-e3e4edb52ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f217be55c0bf</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[José Luis González Sánchez]]></dc:creator>
            <pubDate>Tue, 16 May 2023 12:03:09 GMT</pubDate>
            <atom:updated>2023-05-16T15:43:55.266Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating Your Reactive REST API with Kotlin and Ktor Part I</h3><h3>Introduction</h3><p>One of the essential things that any backend developer must master is creating REST services.</p><p>At present, the management of resources efficiently and effectively is a plus that we must achieve. Reactive programming offers us solutions to the demand for faster response times and high availability of the systems, characteristics achieved with previous models of Microservices, but giving solutions to the problems of excessive use of CPU, blocks in input and output operations, or on memory usage (due to large thread pools) that these models suffered from.</p><p>Throughout this series of articles, a series of contents are presented that you will learn through the different <a href="https://hyperskill.org/tracks?utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor&amp;utm_term=16.05.2023">Hyperskill</a> training tracks. <strong>With Hyperskill you will be able to deepen them, expand them, analyze different alternatives, and become a true backend developer.</strong></p><p>In these tutorials we show how to set up a reactive REST API using Ktor and Kotlin, analyzing all the elements, using Railway Oriented Programming, dependencies injection, testing and applying various security, authentication, and authorization configurations until you can deploy it and enjoy your achievements. Remember that this code is pedagogical, and shows many of the contents that you will learn in <a href="https://hyperskill.org/tracks?utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor&amp;utm_term=16.05.2023">Hyperskill</a> in a didactic and easy-to-read way. It is not intended to create the best production code in real environments.</p><figure><img alt="Creating Your Reactive REST API with Kotlin and Ktor Part I" src="https://cdn-images-1.medium.com/max/1024/1*6sqcDNSinKG2uQb7UrJB7A.png" /><figcaption>Creating Your Reactive REST API with Kotlin and Ktor Part I</figcaption></figure><h3>Reactive Programming</h3><p>Following the principles of the <a href="https://www.reactivemanifesto.org/">Reactive Manifesto</a>, reactive systems must be:</p><ul><li>Responsive: The system responds in a timely manner if at all possible.</li><li>Resilient: The system stays responsive in the face of failure.</li><li>Elastic: The system stays responsive under varying workloads.</li><li>Message Driven: Reactive Systems rely on asynchronous message-passing to establish a boundary between components that ensures loose coupling, isolation, and location transparency.</li></ul><figure><img alt="Reactive programming focuses on working with asynchronous streams from finite or infinite data sources where we can observe them." src="https://cdn-images-1.medium.com/max/1024/1*KsJp6dTuXR-nPzaJXlKHiQ.png" /><figcaption>Figure by <a href="https://www.reactivemanifesto.org/">https://www.reactivemanifesto.org/</a></figcaption></figure><p><strong>Reactive programming focuses on working with asynchronous streams from finite or infinite data sources where we can observe them</strong>.</p><p>Reactive programming is a subset of asynchronous programming. It supports decomposing the problem into multiple discrete steps where each can be executed in an<strong> asynchronous and non-blocking way</strong> and then be composed to produce the final workflow.</p><p>Reactive Programming offers several advantages, including<strong> improved utilization of computing resources on multi-core and multi-CPU</strong> systems and enhanced performance by reducing serialization points. Another significant benefit is increased developer productivity. Traditional programming paradigms have struggled to provide a straightforward and maintainable way of dealing with asynchronous and non-blocking computation and I/O. Reactive Programming solves most of these challenges by eliminating the need for explicit coordination between active components.</p><p>To leverage asynchronous execution, back-pressure must be included to avoid over-utilization or unbounded consumption of resources. For example, in inputs and outputs with databases using JDBC, we block the thread until we get a response. This is a simple example of the things that we are going to solve to improve the productivity of our services.</p><figure><img alt="For example, in inputs and outputs with databases using JDBC, we block the thread until we get a response. This is a simple example of the things that we are going to solve to improve the productivity of our services." src="https://cdn-images-1.medium.com/max/653/1*ERXJmA1XHPcCccFJPDlLyg.png" /><figcaption>Figure by <a href="https://kb.novaordis.com/index.php/Reactive_Programming">https://kb.novaordis.com/index.php/Reactive_Programming</a></figcaption></figure><p>This is where Ktor and Kotlin are an invincible team. <a href="https://ktor.io/">Ktor</a> offers us the possibility of creating asynchronous services (first condition), and <a href="https://kotlinlang.org/">Kotlin</a> offers coroutines and <a href="https://kotlinlang.org/docs/flow.html">Flows</a> to process collections asynchronously and reactively.</p><h3>Creating a new project with Kotlin and Ktor</h3><p><strong>Kotlin</strong> is a statically typed programming language that has several advantages over other programming languages. Some of the advantages of Kotlin are: interoperability with Java, concise syntax, null safety, functional programming support, extension functions, and coroutines which makes it easier to write asynchronous and non-blocking code. Coroutines are lightweight and efficient and can be used to simplify complex asynchronous code. Kotlin support is a great choice for building modern applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCwpKaSY_hTRJMvTddpMAw.png" /></figure><p><strong>Ktor</strong> is a Kotlin-based lightweight framework used to create server-side applications and web services. It provides a simple and flexible API for building asynchronous, event-driven, and non-blocking applications.</p><p>With Ktor, developers can easily create RESTful APIs, web applications, and microservices. It is an open-source framework that can be used for building both web and mobile applications. Ktor can be used with Kotlin coroutines and flows to write asynchronous/reactive code in a more concise and readable style.</p><p>Ktor uses plugins to extend its functionality to the needs of the project. Some of them are included by default, others must be installed. In both cases, we must configure them to be able to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aBfRqsFco67-aiA1EFFmg.png" /></figure><p>We can create a Ktor project from the web generator:<a href="https://start.ktor.io/"> https://start.ktor.io/</a> (open the zip file) or from the <a href="https://ktor.io/create/">IntellIjIdea</a> plugin.</p><p>In our case, as we are experiencing numerous tennis tournaments, we are going to implement <strong>a reactive rest API to find out the most used rackets in a tennis tournament</strong>.</p><p>We must first create our project and add the following plugins: <strong>routing and Kotlin serialization</strong>. The first of them will allow us to create the routes or endpoints to manage the rackets. The second offers us the ability to exchange information in JSON.</p><p>We may need other plugins in the future, but it doesn’t matter, we’ll do it manually later.</p><p>In Adjust project settings, we select “<strong>configuration in HOCON file</strong>”.</p><figure><img alt="Creating Ktor service using https://start.ktor.io/" src="https://cdn-images-1.medium.com/max/888/1*G8VBnzaJMzSEyhtWW_l6vw.png" /><figcaption>Creating Ktor service using <a href="https://start.ktor.io/">https://start.ktor.io/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*-KUwnLGgUIXZWK6UyDHMmg.png" /></figure><figure><img alt="Creating Ktor service with the IntellIj plugin" src="https://cdn-images-1.medium.com/max/767/1*5V4gTZMg381CatzYGDs8Cw.png" /><figcaption>Creating Ktor service with the IntellIj plugin</figcaption></figure><h4>Analyzing the initial code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*mVhfQodrH_jzvcacoiWE7g.png" /><figcaption>Inital strctutre of the project</figcaption></figure><p>We have the following structure:</p><ul><li>Application: It has the code that launches our service and where the plugins to configure are indicated.</li><li>plugins/Routing: Define the routing of our application based a</li><li>plugins/Serialization: Configure the serialization of our application based on JSON</li><li>resources/application.conf: Configure the application based on the environment variables.</li></ul><h4>Configure a Plugin</h4><p>You can configure a plugin using extension functions. For example, configureRouting in Application.kt is an extension function that defines routing. This function is declared in a separate plugin package (the Routing.kt file).</p><pre>fun Application.configureRouting() {<br>   routing {<br>       get(&quot;/&quot;) {<br>           call.respondText(&quot;Hello World!&quot;)<br>       }<br>   }<br>}</pre><h4>Execute the Service</h4><p>You can execute the main method, and then you can check your API on <a href="http://0.0.0.0:8080/">http://0.0.0.0:8080</a>. You can see the famous message: “Hello World!”</p><h3>Coding our service</h3><h4>Configure our service</h4><p>The first step is to configure sour service and add some extra points to our initial <strong>application.conf</strong> to optimize development. This is the first version, and we will expand this file in subsequent tutorials.</p><h4>Define our model</h4><p>The first step is to define our model. In this case, it is Racket. We will do it inside a racket folder/package. It will have an id, brand, model, price, and number of tennis players who use it, image and the instant of creation and last modification. Also, we use a id constant to identify new or existing rackets.</p><pre>data class Racket(<br>    val id: Long = NEW_RACKET,<br>    val brand: String,<br>    val model: String,<br>    val price: Double,<br>    val numberTenisPlayers: Int = 0,<br>    val image: String = DEFAULT_IMAGE,<br>    val createdAt: LocalDateTime = LocalDateTime.now(),<br>    val updatedAt: LocalDateTime = LocalDateTime.now(),<br>    val isDeleted: Boolean = false<br>) {<br>    companion object {<br>        val NEW_RACKET = -1L<br>        const val DEFAULT_IMAGE =<br>            &quot;https://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Tennis_Racket_and_Balls.jpg/800px-Tennis_Racket_and_Balls.jpg&quot;<br>    }<br>}</pre><h4>Developing our repository</h4><p>The repository pattern is a design pattern that isolates the data layer from the rest of the app. The repository pattern has two purposes; first, it is an abstraction of the data layer, and second, it is a way of centralizing the handling of the domain objects. The idea is to have a generic abstract way for the app to work with the data layer without being bothered if the implementation is towards a local database, file, or a memory collection.</p><p>The methods are based on <strong>CRUD — </strong>Create, Read, Update, and Delete. In the first version, we used a <strong>map as a memory repository </strong>(in future parts we will use a reactive database). We use suspended functions, flows, and nullable types to perform the reactive and asynchronous use of the repository. We will use interfaces to be able to perform dependency injection later and comply with SOLID principles. We use <a href="https://github.com/oshai/kotlin-logging">Kotlin Logging</a> to show the messages. Also, we use a new <a href="https://kotlinlang.org/docs/coroutine-context-and-dispatchers.html">context and dispatcher</a> to execute the methods in a special thread not to suspend the thread of the request petition.</p><pre>class RacketsRepositoryImpl : RacketsRepository {<br>   private val rackets = racketsDemoData()<br><br>   override suspend fun findAll(): Flow&lt;Racket&gt; = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;findAll&quot; }<br><br>       return@withContext rackets.values.toList().asFlow()<br>   }<br><br>   override suspend fun findById(id: Long): Racket? = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;findById: $id&quot; }<br><br>       return@withContext rackets[id]<br>   }<br><br>   override suspend fun findAllPageable(page: Int, perPage: Int): Flow&lt;Racket&gt; = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;findAllPageable: $page, $perPage&quot; }<br><br><br>       val myLimit = if (perPage &gt; 100) 100L else perPage.toLong()<br>       val myOffset = (page * perPage).toLong()<br><br>       return@withContext rackets.values.toList().subList(myOffset.toInt(), myLimit.toInt()).asFlow()<br>   }<br><br><br>   override suspend fun findByBrand(brand: String): Flow&lt;Racket&gt; = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;findByBrand: $brand&quot; }<br>       return@withContext rackets.values<br>           .filter { it.brand.contains(brand, true) }<br>           .asFlow()<br>   }<br><br>   override suspend fun save(entity: Racket): Racket = withContext(Dispatchers.IO) {<br>       logger.debug { &quot;save: $entity&quot; }<br><br>       if (entity.id == Racket.NEW_RACQUET) {<br>           create(entity)<br>       } else {<br>           update(entity)<br>       }<br>   }<br><br>   private fun update(entity: Racket): Racket {<br>       logger.debug { &quot;update: $entity&quot; }<br>       <br>       rackets[entity.id] = entity.copy(updatedAt = LocalDateTime.now())<br>       return entity<br>   }<br><br>   private fun create(entity: Racket): Racket {<br>       logger.debug { &quot;create: $entity&quot; }<br>       <br>       val id = rackets.keys.maxOrNull()?.plus(1) ?: 1<br>       val newEntity = entity.copy(id = id, createdAt = LocalDateTime.now(), updatedAt = LocalDateTime.now())<br>       rackets[id] = newEntity<br>       return newEntity<br>   }<br><br>   override suspend fun delete(entity: Racket): Racket? {<br>       logger.debug { &quot;delete: $entity&quot; }<br>       <br>       return rackets.remove(entity.id)<br>   }<br><br>   override suspend fun deleteAll() {<br>       logger.debug { &quot;deleteAll&quot; }<br>       <br>       rackets.clear()<br>   }<br><br>   override suspend fun saveAll(entities: Iterable&lt;Racket&gt;): Flow&lt;Racket&gt; {<br>       logger.debug { &quot;saveAll: $entities&quot; }<br>       <br>       entities.forEach { save(it) }<br>       return entities.asFlow()<br>   }<br>}</pre><h4>Setting our routes and endpoints</h4><p>The next step is to define our routes for our endpoint; for this, we must know perfectly the <a href="https://developer.mozilla.org/es/docs/Web/HTTP/Methods">HTTP verbs</a> and<a href="https://developer.mozilla.org/es/docs/Web/HTTP/Status"> status codes</a> and the <a href="https://ktor.io/docs/requests.html">Request</a> and <a href="https://ktor.io/docs/responses.html">Response</a> using Ktor DSL. We can use this table:</p><figure><img alt="Endpoits of our service" src="https://cdn-images-1.medium.com/max/667/1*ontd8poQrEWLIsMzy0QYpQ.png" /><figcaption>Endpoits of our service</figcaption></figure><p>We use an extension function called “<strong>racketsRoutes()</strong>” to define it, and use this function in our <strong>Routing</strong> plugging.</p><pre>fun Application.configureRouting() {<br>    routing {<br>        get(&quot;/&quot;) {<br>            call.respondText(&quot;Hello World!&quot;)<br>        }<br>    }<br><br>    // Add our routes<br>    racketsRoutes()<br>}</pre><p><strong>Remember, this is not the final version, and we need to improve many things, but this is a good starting point to check our service and how Ktor works.</strong></p><pre>// Define endpoint<br>private const val ENDPOINT = &quot;api/rackets&quot;<br><br>fun Application.racketsRoutes() {<br><br>   // Repository<br>   val rackets: RacketsRepository = RacketsRepositoryImpl()<br><br>   // Define routing based on endpoint<br>   routing {<br>       route(&quot;/$ENDPOINT&quot;) {<br><br>           // Get all rackets --&gt; GET /api/racquets<br>           get {<br>               logger.info { &quot;Get all rackets&quot; }<br><br>               // QueryParams ??<br>               val page = call.request.queryParameters[&quot;page&quot;]?.toIntOrNull()<br>               val perPage = call.request.queryParameters[&quot;perPage&quot;]?.toIntOrNull() ?: 10<br><br>               if (page != null &amp;&amp; page &gt; 0) {<br>                   logger.debug { &quot;GET ALL /$ENDPOINT?page=$page&amp;perPage=$perPage&quot; }<br><br>                   rackets.findAllPageable(page - 1, perPage).toList()<br>                       .run { call.respond(HttpStatusCode.OK, this) }<br><br>               } else {<br>                   logger.debug { &quot;GET ALL /$ENDPOINT&quot; }<br><br>                   rackets.findAll().toList()<br>                       .run { call.respond(HttpStatusCode.OK, this) }<br>               }<br>           }<br><br>           // Get one racket by id --&gt; GET /api/rackets/{id}<br>           get(&quot;{id}&quot;) {<br>               logger.debug { &quot;GET BY ID /$ENDPOINT/{id}&quot; }<br><br>               val id = call.parameters[&quot;id&quot;]?.toLongOrNull()<br>               id?.let {<br>                   rackets.findById(it)?.run { call.respond(HttpStatusCode.OK, this) }<br>                       ?: call.respond(HttpStatusCode.NotFound, &quot;Racket not found with ID $id&quot;)<br>               } ?: call.respond(HttpStatusCode.BadRequest, &quot;ID is not a number&quot;)<br>           }<br><br>           // Get one rackets by brand --&gt; GET /api/rackets/brand/{brand}<br>           get(&quot;brand/{brand}&quot;) {<br>               logger.debug { &quot;GET BY BRAND /$ENDPOINT/brand/{brand}&quot; }<br><br>               val brand = call.parameters[&quot;brand&quot;]<br>               brand?.let {<br>                   rackets.findByBrand(it).toList()<br>                       .run { call.respond(HttpStatusCode.OK, this) }<br>               } ?: call.respond(HttpStatusCode.BadRequest, &quot;Brand is not a string&quot;)<br>           }<br><br>           // Create a new racket --&gt; POST /api/rackets<br>           post {<br>               logger.debug { &quot;POST /$ENDPOINT&quot; }<br><br>               val racket = call.receive&lt;Racket&gt;()<br>               rackets.save(racket)<br>                   .run { call.respond(HttpStatusCode.Created, this) }<br>           }<br><br>           // Update a racket by id --&gt; PUT /api/rackets/{id}<br>           put(&quot;{id}&quot;) {<br>               logger.debug { &quot;PUT /$ENDPOINT/{id}&quot; }<br><br>               val id = call.parameters[&quot;id&quot;]?.toLongOrNull()<br>               id?.let {<br>                   val racket = call.receive&lt;Racket&gt;()<br>                   // exists?<br>                   rackets.findById(it)?.let {<br>                       rackets.save(racket)<br>                           .run { call.respond(HttpStatusCode.OK, this) }<br>                   } ?: call.respond(HttpStatusCode.NotFound, &quot;Racket not found with ID $id&quot;)<br>               } ?: call.respond(HttpStatusCode.BadRequest, &quot;ID is not a number&quot;)<br>           }<br><br>           // Delete a racket by id --&gt; DELETE /api/racquets/{id}<br>           delete(&quot;{id}&quot;) {<br>               logger.debug { &quot;DELETE /$ENDPOINT/{id}&quot; }<br><br>               val id = call.parameters[&quot;id&quot;]?.toLongOrNull()<br>               id?.let {<br>                   // exists?<br>                   rackets.findById(it)?.let { racquet -&gt;<br>                       rackets.delete(racquet)<br>                           .run { call.respond(HttpStatusCode.NoContent) }<br>                   } ?: call.respond(HttpStatusCode.NotFound, &quot;Racket not found with ID $id&quot;)<br>               } ?: call.respond(HttpStatusCode.BadRequest, &quot;ID is not a number&quot;)<br>           }<br>       }<br>   }<br>}</pre><h3>Testing in Postman</h3><p>Finally we can test our API rest in <a href="https://www.postman.com/">Postman</a> or any REST Client. Postman is a famous client to test API REST. You can configure our request and test the responses.</p><figure><img alt="Get all the rackets" src="https://cdn-images-1.medium.com/max/813/1*MBybxX-nRcHouQWwjv2YlQ.png" /><figcaption>Get all the rackets</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*Fje9jv8oeYOi7uCAFQStPA.png" /><figcaption>Get a racket by ID</figcaption></figure><figure><img alt="Post a new racket" src="https://cdn-images-1.medium.com/max/828/1*z9v0iFFz1h5774Lrjau8hw.png" /><figcaption>Post a new racket</figcaption></figure><figure><img alt="Update a racket with a ID" src="https://cdn-images-1.medium.com/max/833/1*cGxtQGcE1j3I5QogUkkqcg.png" /><figcaption>Update a racket with a ID</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*ZExKX_rc9GGO9xRjx2I_rw.png" /><figcaption>Delete a racket by a ID</figcaption></figure><h3>Wrapping up</h3><p>We started a series of exciting topics to capture the ideas of reactive programming to generate API REST.</p><p>Now we have a good starting point to begin working on. We have shown how Ktor works to develop a Reactive API REST, but we need to improve a lot of our code. But not everything can be done in the first step. Little by little, we will learn what we need in the following tutorials.</p><p>We have focused on creating our first endpoints and testing them on Postman. But we still have a lot to do in future tutorials.</p><ul><li>Validate Requests.</li><li>Errors and Exceptions.</li><li>Railway Oriented Programming.</li><li>Using a Cache method.</li><li>Using a Reactive Database.</li><li>Upload files.</li><li>Using web sockets to implement real-time notifications.</li><li>Using Koin to inject our dependencies.</li><li>Security connections with SSL</li><li>Authentication and Authorization with JWT</li><li>Test our endpoints.</li></ul><p>You have the code of this project in: <a href="https://github.com/joseluisgs/ktor-reactive-rest-hyperskill">https://github.com/joseluisgs/ktor-reactive-rest-hyperskill</a>. The code of this part is this link: <a href="https://github.com/joseluisgs/ktor-reactive-rest-hyperskill/releases">https://github.com/joseluisgs/ktor-reactive-rest-hyperskill/releases</a>. Please don’t forget give a star or follow me to be aware of new tutorials and news.</p><p><strong>You can follow it commit by commit and use the Postman backup file to test it.</strong></p><p>In addition, in <a href="http://v/"><strong>Hyperskill</strong></a>, You can deepen and learn all the concepts and more through different topics and tasks that will help you improve as a developer in Kotlin technologies.</p><p>The following tracks <strong>offered by JetBrains Academy on Hyperskill</strong> can be a perfect starting point. You will find all the information and explanation of concepts and techniques shown in these articles. Don’t miss them!</p><ul><li><a href="https://hyperskill.org/tracks/3?category=4&amp;utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor&amp;utm_term=16.05.2023">Kotlin Developer</a></li><li><a href="https://hyperskill.org/tracks/45?category=20&amp;utm_source=medium_hs&amp;utm_medium=social&amp;utm_campaign=ktor&amp;utm_term=16.05.2023">Kotlin Backend Developer (Ktor</a>)</li></ul><p>With these tracks, you will gain practical experience working with modern tools and learn how to develop server-side applications, keep the data in your databases persistent, and test the functionality of your apps using modern tools.</p><p>Let us know in the comments below if you have any questions or feedback regarding this blog. You can also follow us on social media to stay up-to-date with our latest articles and projects. We are on <a href="https://www.reddit.com/r/Hyperskill/">Reddit</a>, <a href="https://www.linkedin.com/company/hyperskill">LinkedIn</a> and <a href="https://www.facebook.com/myhyperskill">Facebook</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f217be55c0bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hyperskill/creating-your-reactive-rest-api-with-kotlin-and-ktor-part-i-f217be55c0bf">Creating your reactive REST API with Kotlin and Ktor part I</a> was originally published in <a href="https://medium.com/hyperskill">Hyperskill</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>