책 검색 앱 (4)
Jan 15, 2026

Open API란?네이버 책 검색 Open API 키 발급오픈 API 사용 규정 확인하기API 호출하기응답값(JSON)을 객체화 처리하기 = 모델 클래스 생성1. 변수 선언 & 기본 생성자2. fromJson 네임드 생성자 & toJson 메서드 만들기3. 모델 클래스 테스트1. test 파일 생성2. Map으로 변환 → 3. 객체로 변환4. test 실행하기5. toJson() 정상 작동 확인
Open API란?
- Open Application Programming Interface
- 특정 서비스나 소프트웨어 기능을 외부 개발자가 사용할 수 있도록 정의한 인터페이스
- 우리가 사용할 네이버 책 검색 API의 경우 우리가 검색어를 네이버에 요청하면 네이버에서 그에 대한 결과를 JSON 형태로 반환해주는 서비스
네이버 책 검색 Open API 키 발급


등록하기를 누르면 client ID와 client Secret 을 확인할 수 있다. 각각 복사해서 저장해두기.오픈 API 사용 규정 확인하기

문서 → 서비스 API → 검색

책 → 책 검색 결과 조회 → 우리는 JSON 형태로 받을 것이므로 두 번째 URL에 해당함.
= 이 URL로 요청을 하면 네이버에서 JSON 형태로 답을 돌려주겠다.
반환형식 JSON인 URL도 복사하여 메모해두기.
파라미터

필수인 파라미터
query 는 필수로 넘겨줘야. → “검색어”에 해당.넘겨줘야 하는 값은 get 요청에서 파라미터를 넘겨줄 때 url 제일 뒤에 물음표
?를 붙이고 key=value 형태로 넘겨준다.파라미터가 여러개인 경우
&, 앰버샌드 연산자로 구분을 지어서 여러 값들을 넘겨준다.https://openapi.naver.com/v1/search/book.json?key=value&key2=value2&key3=value3
우리는 파라미터로
query 를 넘겨줘야 하므로 key값에 query를 입력하고, 입력값은 비워놓는다.https://openapi.naver.com/v1/search/book.json?query=

다음의 정보들도 복붙하여 메모해두기
X-Naver-Client-Id
X-Naver-Client-SecretAPI를 호출할 때는 API 키를 필수적으로 넣어야 하기 때문에 브라우저에서는 API를 호출할 수 없다.
API 호출하기


요 아이콘 (Extensions) 클릭

Thunder Client 인스톨
Thunder Client : 다양한 HTTP 요청을 테스트해 볼 수 있는 도구.cf.
포스트맨 : 현업에서는 이것도 많이 사용. 썬더클라이언트가 훨씬 가벼워서 이걸로 ㄱㄱ.
설치된 썬더 클라이언트 아이콘 클릭
→ New Request 클릭
GET url에 아까 query 키를 입력해둔 url을 넣어준다.→ query 값에
harry라고 넣어준다.https://openapi.naver.com/v1/search/book.json?query=harry
Query 옆에 Headers 클릭헤더에 값을 넣어서 보내줘야 한다. → 헤더는 나중에 REST API 다룰 때 한 번 더 살펴보기로.

아까 메모해두었던 X-Naver-Client-Id를 헤더에, 메모해두었던 API ID를 헤더값에 넣어준다.
cilent-secret도 동일하게 해주고
파란색 Send 버튼 클릭하면 ⇒ 응답값이 패널에 뜬다.
응답값(JSON)을 객체화 처리하기 = 모델 클래스 생성
응답 패널에 뜬 응답값 중
line 6 - "items"에 들어있는 오브젝트들만 객체화처리 할 것임. (what we need)items 하위의
{}로 묶인 덩어리 하나를 중괄호까지 포함하여 복사하여 샘플데이터로 활용한다.
프로젝트로 돌아와서 데이터 폴더 밑에 있는 모델 폴더 하위에
book.dart 파일을 생성한다.파일 내에
Book 클래스를 만들어준다.1. 변수 선언 & 기본 생성자
아까 API 응답값에서 확인한 items의 샘플을 가져와서 최상단에 주석처리 해두고,
필요한 파라미터들을 변수선언 및 생성자 생성 한다.
// {
// "title": "Harry",
// "link": "https://search.shopping.naver.com/book/catalog/54297850481",
// "image": "https://shopping-phinf.pstatic.net/main_5429785/54297850481.20250419202246.jpg",
// "author": "",
// "discount": "0",
// "publisher": "Anson Street Press",
// "pubdate": "20250328",
// "isbn": "9781023086219",
// "description": "\"Harry\" by Fanny Wheeler Hart offers a poignant glimpse into American domestic life through verse. This collection of biographical poetry explores themes of childhood and family, painted with the delicate brushstrokes of personal experience. Hart's work provides a window into a specific time, yet the emotions and experiences it captures resonate across generations."
// }
// cf. 주석처리 하고자 하는 여러 라인을 드래그하여 `ctrl+?` 또는 `command+?`를 누르면 일괄 주석처리 됨.
class Book {
String title;
String link;
String image;
String author;
String discount;
String publisher;
String pubdate;
String isbn;
String description;
Book({
required this.title,
required this.link,
required this.image,
required this.author,
required this.discount,
required this.publisher,
required this.pubdate,
required this.isbn,
required this.description,
});
}2. fromJson 네임드 생성자 & toJson 메서드 만들기
// 1. fromJson 네임드 생성자 만들기
Book.fromJson(Map<String, dynamic> map) : this(
title: map['title'],
link: map['link'],
image: map['image'],
author: map['author'],
discount: map['discount'],
publisher: map['publisher'],
pubdate: map['pubdate'],
isbn: map['isbn'],
description: map['description'],
);
// 2. toJson 메서드 만들기
Map<String, dynamic> toJson() {
return {
'title': title,
'link': link,
'image': image,
'author': author,
'discount': discount,
'publisher': publisher,
'pubdate': pubdate,
'isbn': isbn,
'description': description
};
}3. 모델 클래스 테스트
1. test 파일 생성
프로젝트의 test 폴더로 이동.

new file →
book_model_test.dart 파일 생성test 함수를 활용한다.
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Book model test', () { // <- test() 함수 호출 시 자동완성에 의해 flutter_test.dart를 import하라는 메세지가 나옴. 그걸 적용해주어야 함. test("여기에는 테스트 내용 적고", () {여기에는 실행할 데이터 넣어줌}); <- 함수니까 마무리에는 세미콜론 넣어줘야.
String dummyData = ''' // <- 모델 클래스에 주석처리해두었던 것을 복붙 후 주석 해제
{
"title": "Harry",
"link": "https://search.shopping.naver.com/book/catalog/54297850481",
"image": "https://shopping-phinf.pstatic.net/main_5429785/54297850481.20250419202246.jpg",
"author": "",
"discount": "0",
"publisher": "Anson Street Press",
"pubdate": "20250328",
"isbn": "9781023086219",
"description": "\"Harry\" by Fanny Wheeler Hart offers a poignant glimpse into American domestic life through verse. This collection of biographical poetry explores themes of childhood and family, painted with the delicate brushstrokes of personal experience. Hart's work provides a window into a specific time, yet the emotions and experiences it captures resonate across generations."
}
''';
});
}2. Map으로 변환 → 3. 객체로 변환
import 'dart:convert';
import 'package:book_search/data/models/book.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Book model test', () {
String dummyData = '''
{
"title": "Harry",
"link": "https://search.shopping.naver.com/book/catalog/54297850481",
"image": "https://shopping-phinf.pstatic.net/main_5429785/54297850481.20250419202246.jpg",
"author": "",
"discount": "0",
"publisher": "Anson Street Press",
"pubdate": "20250328",
"isbn": "9781023086219",
"description": "\"Harry\" by Fanny Wheeler Hart offers a poignant glimpse into American domestic life through verse. This collection of biographical poetry explores themes of childhood and family, painted with the delicate brushstrokes of personal experience. Hart's work provides a window into a specific time, yet the emotions and experiences it captures resonate across generations."
}
''';
// 1. Map으로 변환
Map<String,dynamic> map = jsonDecode(dummyData);
// 2. 객체로 변환
Book book = Book.fromJson(map);
expect(book.pubdate, '20250328'); // 왼쪽에는 실제값, 오른쪽에는 기대값을 넣어줌. 왼쪽과 오른쪽의 값이 다르면 테스트가 종료되면서 fail을 리턴함.
});
}4. test 실행하기

test 함수를 입력한 줄의 왼쪽에 초록색 실행버튼이 생김.
이걸 눌러서 실행하면 하단에
test results 패널이 생기는데, 여기에서 테스트 결과값을 확인할 수 있음.‘The test run did not record any output.’ 이라면 성공.

좌우 값이 상이할 경우 에러 발생하여 확인 가능함.
5. toJson() 정상 작동 확인
expect 함수 아래에
print(book.toJson()); 넣어서 실행해보고 결과값 확인한다.
실행은 7번 라인 옆에 있는 버튼을 눌러서 실행.

여기까지 정상적으로 실행되었다면 테스트 완료!
📍git push
Share article