API(카카오 오픈 API 이용해서 책 검색)
API(Application Programming Interface)
: 응용 프로그램 개발자들이 애플리케이션을 만들 때 운영체제에서 동작하는 프로그램을 쉽게 만들 수 있도록 화면 구성이나 프로그램 동작에 필요한 각종 함수를 모아놓은 것을 말한다.
API 가이드
요청(request) | 응답(response) |
주소 | 형식 |
전송방식 : GET, POST. . . . | 응답 의미 설명 |
보낼 것 query 검색어(필수) sort 정렬 방식(선택) targer 검색 대상(선택) |
# STEP 1. HTML 파일 생성
Download Visual Studio Code - Mac, Linux, Windows
Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows. Download Visual Studio Code to experience a redefined code editor, optimized for building and debugging modern web and cloud applications.
code.visualstudio.com
VSCODE를 열어 Index.html 파일을 생성 후, 기본 HTML5 문서를 생성하고 <title> 태그에 API 연습이라고 적어줍니다.
이 HTML 코드를 변형시키고, API를 이용해서 책 검색을 할 수 있는 사이트를 만들어 보겠습니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API 연습</title>
</head>
JQuery CDN을 이용해서 JQuery를 가져오기 위해 Google에 JQuery CDN을 검색 후, <body> 태그위에 붙히도록 합니다.
jQuery CDN
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libr
releases.jquery.com
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API 연습</title>
</head>
<script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
crossorigin="anonymous"></script>
또한 JQuery를 이용한 AJAX를 사용할 것이기 때문에 JQuery AJAX 공식 API 문서를 활용해서 코드를 작성해보도록 하겠습니다.
jQuery.ajax() | jQuery API Documentation
Description: Perform an asynchronous HTTP (Ajax) request. The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available
api.jquery.com
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});
API Documentation에서 가져온 Example JQuery 코드를 그대로 가져옵니다.
# STEP 2. kakao developers rest API
이제 기본적인 준비는 끝났으니 API 공식 문서를 활용해서 본격적으로 책 검색 서비스를 구현해보도록 하겠습니다.
Kakao Developers
카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.
developers.kakao.com
kakao developers에 접속하여 내 에플리케이션을 추가하여 네이티브 앱 키를 비롯한 4개의 키를 발급받고,
문서 > Daum 검색 > 개발 가이드에 들어와서 책 검색 파트를 참조합니다.
Request 요청에 대한 정보와, Response 응답에 대한 정보를 확인하고, 가이드 문서를 따라 코드를 완성해보도록 하겠습니다.
가이드를 참조해서 method, url, data, headers(발급 받은 rest API 키) 까지 적절하게 넣어주고, 값이 제대로 응답되는지
console.log를 활용해서 object(JSON) 형식의 데이터를 확인해보면 된다.
# STEP 3. JSON 데이터를 가공해서 원하는 서비스를 제작.
AJAX의 data로 쿼리 형식의 책 제목을 입력했더니, 응답 받는 데이터로(documents) title을 비롯하여 contents, url 등등 많은 데이터가 전송되어 오는것을 확인할 수 있다.
우리의 서비스는 책 제목과(title) 책 도서 표지(thumbnail)이므로, html에 <p> 태그를 열어 그 속에 우리가 원하는 데이터를 넣어주면
웹에서는 전송된 데이터를 이용하여 사용자들에게 책 제목과, 표지를 보여주게 된다.
조금 더 활용해서 <input> 태그를 활용해서 모든 책을 검색할 수 있는 서비스를 제공하게 됐다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API 연습</title>
</head>
<script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$("#search").click(function(){
$.ajax({
method: "GET",
url: "https://dapi.kakao.com/v3/search/book?target=title",
data: { query : $("#bookname").val() },
headers : { Authorization: "KakaoAK 26ed6aae306532aaaa1fab31b48340db"}
})
.done(function (msg) {
console.log(msg.documents[0].title);
console.log(msg.documents[0].thumbnail);
$( "p" ).append( "<strong>" + msg.documents[0].title + "</strong>" );
$( "p" ).append( "<img src = '" + msg.documents[0].thumbnail + "'</src>" );
});
});
});
</script>
<body>
<h1>내 사이트임 ㅎㅇ</h1>
<input id = "bookname" value="" type = "text">
<button id = "search"> 검색 </button>
<p></p>
</body>
</html>
오늘은 kakao에서 제공하는 다양한 Open API 중에서 책 검색 API를 활용하여 간단한 서비스를 구현해봤다.
API를 직접 만지고 가공해보니, 굉장히 재밌었고. . . 카카오뿐만아니라 다양한 기업에서 제공하는 여러 API를 만지고
그 API를 가지고 다양한 서비스를 구현할 수 있겠다 라고 생각했다.
특히, 증권회사나 은행에서 제공하는 API를 만져보고 싶다. . . 여러 사용자들의 다양한 금융 사용 분석 데이터를 통해서 다양한 서비스를 새롭게 구현할 수 있을 것 같아서 말이다. 그러기 위해서는 은행이나, 증권회사에서 주최하는 다양한 해커톤에 참여해야하는데 남은 취준 기간동안 꼭 이런 값진 경험을 해보고 싶다.