spring boot - API 생성 방법

최대 1 분 소요

Spring Boot로 개발하는 RESTful Service

REST API 설계

User -> Posts (1대 다 관계)

Description REST API HTTP Method
Retrieve all Users /users GET
Create a User /users POST
Retrieve one User /users/{id} GET
Delete a User /users/{id} DELETE
Retrieve all posts for a User /users/{id}/posts GET
Create a posts for a User /users/{id}/posts POST
Retrieve detail post of a User /users/{id}/posts/{post_id} GET

spring boot 설정

프로젝트 설정

image

Dependencies 설정

image

image

image

spring boot 포트 변경 방법

  • application.properties 파일을 yml 파일로 변경후 아래와 같이 입력 후 실행

    => yml 파일이 보다 직관적임

image

API 생성 방법

/Hello-world api 만들기

image

image

return 타입을 Java Bean형태로 api 만들기

image

HelloWorldBean.java

package com.example.restfulwebservice;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class HelloWorldBean {
    private String message;
}

  • lombok의 @Data, @AllArgsConstructor 애노테이션을 사용

    => HelloWorldBean 이 가지는 모든 필드들에 대해서 getter setter, 생성자, toString 자동생성

    image

image

  • json 형태로 반환되는 것을 확인할 수 있다.

Path Variable 사용해서 api 만들기

http://localhost/users

http://localhost/users/1 or http://localhost/users/5

@GetMapping("/hello-world-bean/path-variable/{name}")
    public HelloWorldBean helloWorldBean(@PathVariable String name) {
        return new HelloWorldBean(String.format("Hello World, %s", name));
    }

image

카테고리:

업데이트:

댓글남기기