Creat REST API using Javalin with Kotlin

--

บทความนี้เราจะมายกตัวอย่างการสร้าง Webservice REST API โดยใช้ Javalin with Kotlin แบบง่ายๆ ฉบับโน๊ตไว้ดูเอง และผื่อเป็นประโยชน์กับคนที่เข้ามาอ่านด้วย

Kotlin เป็นภาษาที่พัฒนาขึ้นมาเพื่อใช้แทนภาษา Java สามารถเข้ากันกับ Java ได้ 100% ละยังใช้ประโยชน์จาก libraries ที่มีอยู่ใน Java ได้

เป้าหมายของ Kotlin คือนำมาใช้แทน JAVA โดยยังรักษาโค้ด JAVA เพื่อให้ทำงานร่วมกับโปรเจคเก่าๆ ที่พัฒนาด้วยภาษา Java ได้

Javalin เป็น Web Framework ตัวนึงในภาษา Kotlin ที่มีน้ำหนักเบามาก สำหรับ kotlin กับ java ที่รองรับ web Sockets Sockets

Rest API คืออะไร ?

Soft waere (ที่ใช้ในการยกตัวอย่าง)

ขั้นตอนการสร้าง Rest API Step by step

  1. Open IntelliJIDEA เพื่อสร้างโปรเจค File >New >Project…

แล้วทำตามภาพตัวอย่างด้านล่าง [8] Finish

รูปภาพตัวอย่างการ Create Project
รูปภาพตัวอย่างโครงสร้าง Project หลังการ Create Project
รูปภาพตัวอย่างโครงสร้าง Project ที่เสร็จแล้ว

2. Open file main.kt ขึ้นมาเพื่อลองรันเทสด้วยการกดคีย์ลัด ⇪⌃R

รูปภาพแสดงตัวอย่างผลลัพธ์ main.kt

3. Open file pom.xml เพิ่ม dependency ดังนี้

  • logback : เป็นตัว log
  • jackson : เป็นไลบรารีการประมวลผล JSON
  • javalin : เป็น Web Framework ตัวนึงในภาษา Kotlin
รูปภาพแสดงตัวอย่างการเพิ่ม dependency เข้ามาใน file pom.xml
ตัวอย่าง file pom.xml ทั้งหมด

4. สร้าง file StringUtil.kt

5. สร้าง file UserDao.kt

6. Update file main.kt แล้วรันที่ file main.kt

ตัวอย่างการ Test REST API Method Get, Post, Patch, Delete

ตัวอย่างการ Test method Post

http://localhost:7000/users/
รูปภาพตัวอย่างการ setting headers in postman
{
"name": "xxxxx",
"email": "xxxx@gmail.com"
}
รูปภาพตัวอย่างการ test method post (ลองยิงดูสัก 2 ครั้ง)

ตัวอย่างการ Test method Get

http://localhost:7000/users/
รูปภาพตัวอย่างการ test method get (กรณี users ทั้งหมด)
http://localhost:7000/users/101
รูปภาพตัวอย่างการ test method get (กรณีค้นหาข้อมูลด้วย id)

ตัวอย่างการ Test method Patch

http://localhost:7000/users/102
รูปภาพตัวอย่างการ setting headers in postman
{
"name": "test",
"email": "test@gmail.com"
}
รูปภาพตัวอย่างการ test method patch

ตัวอย่างการ Test method get (ค้นหาข้อมูลด้วย email)

http://localhost:7000/users/email/test@gmail.com
รูปภาพตัวอย่างการ test method get (กรณีค้นหาข้อมูลด้วย email)

ตัวอย่างการ Test method Delete

http://localhost:7000/users/101
รูปภาพตัวอย่างการ test method delete

*** Source code ***

https://gitlab.com/kotlin15/kotlinapi

*** แหล่งข้อมูล ***

https://javalin.io/tutorials/simple-kotlin-example

--

--

No responses yet