[SpringBoot] π‘ μ¬λ¬κ°μ§ API μμ±λ²
π API
APIλ Application Programming Interface
μ μ½μλ‘ μ΄μ체μ λ μμ©νλ‘κ·Έλ¨ μ¬μ΄μ ν΅μ μ μ¬μ©λλ μΈμ΄λ λ©μΈμ§ νμμ μλ―Ένλ€.
μΌλ°μ μΌλ‘ λ€μμ 4κ°μ§ λ©μλλ₯Ό μ£Όλ‘ μ¬μ©νλ©°, λ€μ κΈ°λ₯μΌλ‘ μ£Όλ‘ μ°μΈλ€.
- GET - read
- POST - create
- PUT - update
- DELETE - delete
π Get λ©μλ
URLμ κ²½λ‘λ νλΌλ―Έν°μ λ³μλ₯Ό λ£μ΄μ μμ²μ 보λ΄λ λ°©μμ΄λ€.
@GetMapping("/getmapping")
public String getMapping() {
return "getMapping";
}
π @pathVariable
@GetMapping("/getmapping2/{variable}")
public String getMapping2(@PathVariable String variable) {
return variable;
}
π @RequestParam
@GetMapping("/getmapping3")
public String getMapping3(
@RequestParam String name,
@RequestParam String email,
@RequestParam String organization) {
return name + " " + email + " " + organization;
}
π DTO κ°μ²΄
π dto
dto packageλ₯Ό λ§λ€μ΄ μ€ ν, dto κ°μ²΄λ₯Ό λ§λ€μ΄μ€λ€.
alt + insert
λ¨μΆν€λ₯Ό ν΅ν΄μ μ½κ² getter & setter μ toStringμ μμ±κ°λ₯νλ€.
dto κ°μ²΄
package com.example.test.dto;
public class MemberDto {
private String name;
private String email;
private String organization;
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "MemberDto{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", organization='" + organization + '\'' +
'}';
}
}
@GetMapping("/getmapping4")
public String getmapping4(MemberDto dto){
return dto.toString();
}
π POST λ©μλ
μ μ₯νκ³ μ νλ 리μμ€λ κ°μ HTTP λ°λ(body)μ λ΄μμ μλ²μ μ λ¬νλ€.
Body
μμμ μμ±λλ κ°μ μΌμ ν ννλ₯Ό μ·¨νλλ°, μΌλ°μ μΌλ‘ JSON
νμμΌλ‘ μ μ‘λλ€.
π DTO κ°μ²΄
@RestController
@RequestMapping("/post")
public class PostController {
@PostMapping("/postmapping1")
public String PostMapping(@RequestBody MemberDto dto){
return dto.toString();
}
}
π PUT λ©μλ
μΉ μ ν리μΌμ΄μ μλ²λ₯Ό ν΅ν΄ λ°μ΄ν°λ² μ΄μ€ κ°μ μ μ₯μμ μ μ₯νλ 리μμ€ κ°μ μ λ°μ΄νΈ νλλ° μ¬μ©νλ€.
π DTO κ°μ²΄
@RestController
@RequestMapping("/put")
public class PutController {
@PutMapping("/putMapping1")
public String putMapping(@RequestBody MemberDto dto){
return dto.toString();
}
}
π DELETE λ©μλ
μΉ μ ν리μΌμ΄μ μλ²λ₯Ό ν΅ν΄ λ°μ΄ν°λ² μ΄μ€ κ°μ μ μ₯μμ μ μ₯νλ 리μμ€ κ°μ μ λ°μ΄νΈ νλλ° μ¬μ©νλ€.
π DTO κ°μ²΄
@RestController
@RequestMapping("/put")
public class PutController {
@PutMapping("/putMapping1")
public String putMapping(@RequestBody MemberDto dto){
return dto.toString();
}
}
κ°μΈ κ³΅λΆ κΈ°λ‘μ© λΈλ‘κ·Έμ
λλ€.
ν리거λ μ€λ₯κ° μμ κ²½μ° μ 보ν΄μ£Όμλ©΄ κ°μ¬νκ² μ΅λλ€.π