티스토리 뷰

간단하게 외부 api 문서 작성할게 있어 도입하고 지속 활용해보기로 결정.

 

이전 기본 설정 이후 test class 작성.

 

하나 예시로 get 방식 api 활용. 

 

@Test
    public void getAlarmHistoryList() throws Exception {
        this.mockMvc.perform(RestDocumentationRequestBuilders.get("/external/getAlarmHistory/{startDate}/{endDate}", "20220629120000", "20220629120500")
                .accept(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
                .andDo(document("alarm-history-get",
                        getDocumentRequest(),
                        getDocumentResponse(),
//                        preprocessRequest(prettyPrint()),
//                        preprocessResponse(prettyPrint()),
                        pathParameters(
                                parameterWithName("startDate").description("조회시작일시"),
                                parameterWithName("endDate").description("조회종료일시")
                                ),
                        responseFields(
                                fieldWithPath("[].alarmMsg").description("알람메시지"),
                                fieldWithPath("[].endDate").description("알람종료시간"),
                                fieldWithPath("[].factoryName").description("공장명"),
                                fieldWithPath("[].lineName").description("라인명"),
                                fieldWithPath("[].machineName").description("설비명"),
                                fieldWithPath("[].alarmType").description("알람타입"),
                                fieldWithPath("[].gapSec").description("알람지속시간(초)"),
                                fieldWithPath("[].startDate").description("알람시작시간"),
                                fieldWithPath("[].factoryId").description("타키온테크 내부 아이디"),
                                fieldWithPath("[].alarmId").description("타키온테크 내부 아이디"),
                                fieldWithPath("[].alarmTypeId").description("타키온테크 내부 아이디"),
                                fieldWithPath("[].alarmStatusId").description("타키온테크 내부 아이디"),
                                fieldWithPath("[].machineId").description("타키온테크 내부 아이디"),
                                fieldWithPath("[].lineId").description("타키온테크 내부 아이디")
                                )
                        ));
    }

 

MockMvc 설정에서 api 방식, 주소, path variable를 작성해주고 andDo 부분에서 요청 및 응답 부분의 표현 방식들을 작성할 수 있었다.

 

andDo 명령어 document에서 generated-snippets 하위단에 저장될 폴더명을 설정할 수 있다.

 

 

document는 RestDocumentationResultHandler와 MockMvcRestDocumentation의 방식들이 있었고 상황에 맞게 사용해주면 됐다.

 

나같은 경우는 표현 uri 변경이 필요하여 후자를 활용해 인터페이스를 작성하고 사용했다.

 

import org.springframework.restdocs.operation.preprocess.OperationRequestPreprocessor;
import org.springframework.restdocs.operation.preprocess.OperationResponsePreprocessor;

import static org.springframework.restdocs.operation.preprocess.Preprocessors.*;

public interface ApiDocumentUtils {
    static OperationRequestPreprocessor getDocumentRequest() {
        return preprocessRequest(
                        modifyUris()
                                .scheme("https")
                                .host("example.com")
                                .removePort(),
                        prettyPrint());
    }

    static OperationResponsePreprocessor getDocumentResponse() {
        return preprocessResponse(prettyPrint());
    }
}

 

위와 같이 작성하고 test class에서 static으로 import 후 getDocumentRequest(), getDocumentResponse() 메서드를 document 안쪽에서 설정해줬다.

 

그러면 mvn install 후 html 파일에 curl 주소가 기본 localhost에서 내가 정해준 주소로 바뀌어 있음을 확인할 수 있다.

 

 

pathParameters를 통해 get api path variable 설명 표현이 가능했다.

 

 

 

responseFields는 응답 파라미터 형식, 타입과 설명을 작성할 수 있었다.

 

 

찾아보니 우아한 형제들에서 정리 작성한 글이 가장 영양가 있었다.

https://techblog.woowahan.com/2597/

 

Spring Rest Docs 적용 | 우아한형제들 기술블로그

{{item.name}} 안녕하세요? 우아한형제들에서 정산시스템을 개발하고 있는 이호진입니다. 지금부터 정산시스템 API 문서를 wiki 에서 Spring Rest Docs 로 전환한 이야기를 해보려고 합니다. 1. 전환하는

techblog.woowahan.com

 

나같이 새로 접하는 사람은 위에 우하한형제들 글을 참고하면 공식 레퍼런스보다 더 쉽게 접근할 수 있을 것 같다.

 

이후 adoc 파일 꾸미는 것 부터 다른 api 방식(post, put)들에 대한 정리를 해야겠다.

'Spring boot > Spring rest docs' 카테고리의 다른 글

01. Spring rest docs - 기본 설치 및 설정  (0) 2022.06.28
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함