Create a simple CRUD application using Ktor and Vue.js


To create a simple CRUD application using Ktor (backend) and Vue.js (frontend), follow these steps:

Backend (Ktor)

  1. Set up Ktor Project:

    • In your build.gradle.kts file, add Ktor dependencies for HTTP, serialization, and PostgreSQL (or another database if preferred):
    plugins {
        kotlin("jvm") version "1.8.0"
        application
    }
    
    dependencies {
        implementation("io.ktor:ktor-server-core:2.2.2")
        implementation("io.ktor:ktor-server-netty:2.2.2")
        implementation("io.ktor:ktor-serialization-kotlinx-json:2.2.2")
        implementation("io.ktor:ktor-server-sessions:2.2.2")
        implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
        implementation("org.jetbrains.exposed:exposed-core:0.41.1")
        implementation("org.jetbrains.exposed:exposed-dao:0.41.1")
        implementation("org.jetbrains.exposed:exposed-jdbc:0.41.1")
        implementation("org.postgresql:postgresql:42.5.0")
        testImplementation("io.ktor:ktor-server-tests:2.2.2")
    }
    
    application {
        mainClass.set("ApplicationKt")
    }
  2. Ktor Application Setup (Application.kt):

    • Create a simple Ktor server with routes for CRUD operations. Here’s an example of setting up a basic CRUD API.
    import io.ktor.application.*
    import io.ktor.features.ContentNegotiation
    import io.ktor.http.HttpStatusCode
    import io.ktor.jackson.jackson
    import io.ktor.response.respond
    import io.ktor.routing.Route
    import io.ktor.routing.get
    import io.ktor.routing.post
    import io.ktor.routing.put
    import io.ktor.routing.delete
    import io.ktor.server.engine.embeddedServer
    import io.ktor.server.netty.Netty
    import io.ktor.server.routing.routing
    import io.ktor.features.ContentNegotiation
    import io.ktor.serialization.kotlinx.json
    import io.ktor.server.application.Application
    import io.ktor.server.response.respond
    import io.ktor.server.routing.Route
    import io.ktor.server.routing.post
    import io.ktor.server.routing.get
    import io.ktor.server.routing.put
    import io.ktor.server.routing.delete
    
    fun Application.module() {
        install(ContentNegotiation) {
            jackson {}
        }
    
        routing {
            route("/api/items") {
                get {
                    // Fetch items from database and respond
                    call.respond(HttpStatusCode.OK, listOf(Item("Item1"), Item("Item2")))
                }
    
                post {
                    // Create a new item
                    call.respond(HttpStatusCode.Created, Item("NewItem"))
                }
    
                put("/{id}") {
                    // Update item by ID
                    call.respond(HttpStatusCode.OK, Item("UpdatedItem"))
                }
    
                delete("/{id}") {
                    // Delete item by ID
                    call.respond(HttpStatusCode.NoContent)
                }
            }
        }
    }
    
    data class Item(val name: String)
  3. Run the Ktor Application: Run the application with:

    ./gradlew run

    This will start the Ktor server, which will be listening on http://localhost:8080.

Frontend (Vue.js)

  1. Set up Vue.js Project:

    • Create a new Vue.js project using Vue CLI:
    vue create crud-vue-app
    • During the setup, select the default configurations.
  2. Install Axios:

    • Install Axios to make HTTP requests:
    npm install axios
  3. Create CRUD Operations in Vue:

    • In src/components/CrudApp.vue, create a simple interface for adding, viewing, updating, and deleting items.
    <template>
      <div>
        <h1>CRUD App</h1>
        <div>
          <input v-model="newItem" placeholder="Enter new item">
          <button @click="createItem">Add Item</button>
        </div>
        <ul>
          <li v-for="item in items" :key="item.name">
            {{ item.name }} 
            <button @click="editItem(item.name)">Edit</button>
            <button @click="deleteItem(item.name)">Delete</button>
          </li>
        </ul>
      </div>
    </template>
    
    <script>
    import axios from 'axios';
    
    export default {
      data() {
        return {
          items: [],
          newItem: ""
        };
      },
      created() {
        this.fetchItems();
      },
      methods: {
        async fetchItems() {
          try {
            const response = await axios.get('http://localhost:8080/api/items');
            this.items = response.data;
          } catch (error) {
            console.error(error);
          }
        },
        async createItem() {
          try {
            await axios.post('http://localhost:8080/api/items', { name: this.newItem });
            this.fetchItems();
            this.newItem = "";
          } catch (error) {
            console.error(error);
          }
        },
        async editItem(name) {
          const updatedName = prompt("Edit item", name);
          if (updatedName) {
            try {
              await axios.put(`http://localhost:8080/api/items/${name}`, { name: updatedName });
              this.fetchItems();
            } catch (error) {
              console.error(error);
            }
          }
        },
        async deleteItem(name) {
          try {
            await axios.delete(`http://localhost:8080/api/items/${name}`);
            this.fetchItems();
          } catch (error) {
            console.error(error);
          }
        }
      }
    };
    </script>
  4. Run the Vue.js Application:

    • In the project folder, run the Vue.js application:
    npm run serve

    This will start the frontend on http://localhost:8081 by default.

Summary:

  • The Ktor backend serves as the API with routes for CRUD operations (GET, POST, PUT, DELETE).
  • Vue.js is used for the frontend to display and interact with items, utilizing Axios to make HTTP requests to the Ktor API.

This creates a simple CRUD application where you can add, edit, view, and delete items.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete