개요
이번 글은 저번 시리즈에 이어서 FIFA ONLINE 4 API를 이용한 게임 통계 웹사이트 제작 2편을 작성하려한다.
이번 시리즈에서는 유저 정보 조회 API를 사용하여 유저 닉네임 검색을 통해 유저의 정보를 받아오고 그 값을 보여주는 단계를 진행 할 예정이다.
API 발급 받기
넥슨 개발자 센터 홈페이지에 접속한다. - https://developers.nexon.com/
로그인을 한 뒤에 마이페이지로 들어가 오른쪽 위의 새 어플리케이션 등록 버튼을 누른다.
새 어플리케이션 등록 탭에서 자신이 사용할 어플리케이션 이름을 입력하고 게임 API로 피파온라인 4, API Key 타입으로 개발을 선택한 이후 어플리케이션을 등록한다.
어플리케이션을 등록한 뒤 다시 마이페이지로 돌아오면 위 사진처럼 어플리케이션이 정상적으로 등록되어 있을 것이다.
Lombok 의존성 추가
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
프로젝트를 좀 더 편리하게 만들기위해 Gradle에 Lombok 의존성을 추가해준다.
AppConfig 클래스 생성
package com.FIFAONLINE4.GG;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.build();
}
}
UserResponseDto 구현
package com.FIFAONLINE4.GG.user;
import lombok.Data;
import lombok.Getter;
@Data
@Getter
public class UserResponseDto {
private String accessId;
private String nickname;
private int level;
}
UserResponseDto 클래스를 생성하고 우리가 API를 통해 받을 수 있는 데이터인 accessId와 nickname, level을 가질 수 있도록 해준다.
UserApiClient 구현
package com.FIFAONLINE4.GG.user;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@RequiredArgsConstructor
@Service
public class UserApiClient {
private final RestTemplate restTemplate;
private final String API_KEY = "자신이 받은 API 키";
private final String userInfoUrl = "https://api.nexon.co.kr/fifaonline4/v1.0/users?nickname={nickname}";
public UserResponseDto requestUserInfo(String nickname) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Authorization", API_KEY);
final HttpEntity<String> entity = new HttpEntity<>(httpHeaders);
return restTemplate.exchange(userInfoUrl, HttpMethod.GET, entity, UserResponseDto.class, nickname).getBody();
}
}
유저의 API 부분을 담당할 UserApiClient 클래스를 생성한다.
이때 비교적 간편하게 API를 호출하기 위해 Spring 내장 클래스인 RestTemplate를 사용하여 Response Body 부분을 받아준다.
혹여나 위 코드를 블로그나 깃허브에 올릴 예정이라면 API 키가 직접적으로 드러나는 부분은 .gitignore를 통해 API 키가 타인에게 노출되지 않도록 설정해준다.
UserService 구현
package com.FIFAONLINE4.GG.user;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@RequiredArgsConstructor
@Service
public class UserService {
private final UserApiClient userApiClient;
public UserResponseDto searchUserInfo(String nickname) {
return userApiClient.requestUserInfo(nickname);
}
}
UserService 클래스를 생성해주고, API 관련 서비스를 처리해줄 수 있도록 구현한다.
UserController 구현
package com.FIFAONLINE4.GG.user;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@RequiredArgsConstructor
@Controller
public class UserController {
private final UserService userService;
private UserResponseDto userInfoDto;
@GetMapping("/user")
public String user(Model model) {
if(userInfoDto != null) {
model.addAttribute("nickName", userInfoDto.getNickname());
model.addAttribute("level", userInfoDto.getLevel());
}
return "user";
}
@GetMapping("api/v1/user/{nickname}")
@ResponseBody
public UserResponseDto getUserInfo(@PathVariable String nickname, Model model) {
userInfoDto = userService.searchUserInfo(nickname);
return userInfoDto;
}
}
UserService 클래스를 생성해주고 API Controller에서 PathVariable을 통해 유저의 닉네임을 받아와 Dto를 리턴해준다.
보여질 부분을 담당할 user에서는 Dto를 통해 받은 값을 뷰에 뿌려줄 수 있도록 한다.
user.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<style>
footer {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
padding: 15px 0;
text-align: center;
color: white;
background: blue;
}
table {
margin-left: auto;
margin-right: auto;
}
</style>
<script type="text/javascript">
function searchInfo() {
const nickname = $('#nickname').val();
$.ajax({
type: 'GET',
url: 'api/v1/user/'+nickname,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
}).done(function (res) {
window.location.reload();
}).fail(function (error){
alert('없는 유저입니다. 다시 입력해주세요.');
});
}
</script>
<head>
<meta charset="UTF-8">
<title>FIFA4-User</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="/button.js"></script>
</head>
<body>
<h1 style="text-align: center">FIFA Online 4 - GG</h1>
<div class="container" style="margin-top: 150px;">
<h3 style="text-align: center">구단주 검색</h3>
<form style="margin: auto; width: 230px">
<div class="input-group">
<input type="text" class="form-control" id="nickname" placeholder="구단주를 입력하세요">
<button class="btn btn-primary" type="button" id="search-info" onclick="searchInfo()">검색</button>
</div>
</form>
</div>
<p>
<table class="table table-horizontal table-bordered">
<thead class="thead-strong">
<tr>
<th>구단주 이름</th>
<th>레벨</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td th:text="${nickName}"></td>
<td th:text="${level}"></td>
</tr>
</tbody>
</table>
</p>
<footer>
<h4>Data based on NEXON DEVELOPERS</h4>
</footer>
</body>
</html>
위와 같이 유저 닉네임을 인풋 박스에 입력하고 검색 버튼을 누르면 API 호출을 통해 JSON 형식으로 데이터를 받아올 수 있고, Dto를 통해 우리가 직접 해당 유저의 닉네임과 레벨을 확인할 수 있다.
accessId까지 보여주고 싶으면 user쪽 Controller와 user.html을 조금만 수정하면 된다.
View
참고
https://nam-ki-bok.github.io/spring/UserInfo/
[FIFA Online TMI] 넥슨 Open API로 유저 정보 가져오기
1 DAY 1 UPLOAD
nam-ki-bok.github.io
소스
https://github.com/Camelllia/FIFAONLINE4-GG
GitHub - Camelllia/FIFAONLINE4-GG: 피파온라인4 API를 사용한 게임 통계 사이트
피파온라인4 API를 사용한 게임 통계 사이트. Contribute to Camelllia/FIFAONLINE4-GG development by creating an account on GitHub.
github.com