API 101 PART 2 My First API in my life กับ Web Service อันแสนวุ่นวาย


ความเดิมตอนที่แล้ว…

ผลการค้นหารูปภาพสำหรับ Spring boot

มาถึงกันแล้วกับ PART 2 รอบนี้เนี่ย หลังจากที่ดูเรื่องของ API และ Web Service แบบเบื้องต้นไปแล้วทีนี้ก็มาถึงการลองทำแล้วซึ่งการทำ API รอบนี้มันเป็นการทำแบบ REST API นะครับบนพื้นฐานของ framework ของ Java ที่มีชื่อว่า Spring boot และ Maven ที่สำคัญก็ต้องทำ Code ทำแบบ Micro Service ด้วยบอกเลยว่าครั้งนี้พลาดอย่างแรงเพราะอะไรหน่ะหรอมาดูกันว่าเกิดอะไรขึ้นในการบ้านที่ได้ลองทำ (ขออนุญาตข้ามขั้นตอนการติดตั้งไปนะครับและการทำ API นี้ยังคงยึดหลักของ MVC เหมือนเดิมอ่านะ ใครลืมก็ อย่ายอมจำนน นะฮะ #ผิด แล้วที่สำคัญก็ยังใช้หลักการและอะไรๆคล้ายๆในวิชา INT303 อีกด้วย งั้นข้ามเลย) เดี๋ยวไปดูเลยดีกว่า ว่าทำอะไรไปทำไมถึงว่าพลาด…

User Model

package th.ac.kmutt.sit.MyFirstService.controller;public class User {

private int id;
private String name;
public User() {}public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}

User Controller

package th.ac.kmutt.sit.MyFirstService.controller;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
@RestController
public class UserController {
@GetMapping("/")
public String testAPI() {
return "Your API is working!!";
}
@GetMapping("/user/1")
public User getUserId1() {
return new User(1, "Phornlert");
}
@GetMapping("/user/2")
public User getUserId2() {
return new User(2, "Allen");
}
@GetMapping("/user/3")
public User getUserId3() {
return new User(3, "Panya");
}
@GetMapping("/user/4")
public User getUserId4() {
return new User(4, "Paapan");
}
@GetMapping("/user/5")
public User getUserId5() {
return new User(5, "NewUser");
}
//Return all user's object in an Arraylist
@GetMapping("/users")
public ArrayList<User> getUsers() {
ArrayList user = new ArrayList();
user.add(new User(1, "Phornlert"));
user.add(new User(2, "Allen"));
user.add(new User(3, "Panya"));
user.add(new User(4, "Paapan"));
user.add(new User(5, "NewUser"));
return user;
}
}

มีใครสังเกตอะไรไหม??? ใช่แล้ว Controller นั้นมี Method 1 ตัวที่ทำมากกว่า 1 อย่างไงหล่ะ ซึ่งมันอยู่ในส่วนของ Controller ใน Method ที่มีชื่อว่า getUsers() ไงหล่ะ

ปกติแล้วการทำ Code เพื่อการทำ Micro Service นั้น 1 Method นั้นควรจะทำเพียงแค่อย่างเดียวยังไงหล่ะ ทำไมต้องเป็นแบบนี้หน่ะหรองั้นเดี๋ยวไปต่อกันใน PART อื่นกันเลยเพราะว่าอาทิตย์นี้ (1–9–2561) ได้เรียนเรื่อง Micro Service และได้เจาะลึกเรื่อง HTTP Protocol อีกด้วย ไว้รออ่านกันน้าาา

ปล.มีการโดนสั่งเขียน Unit Test อีกต่างหาก TT

ตอนต่อไป

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade