[Fetch API&AXIOS] 공공데이터포털 API 사용해 보기
1. 원하는 API를 선택
선택한 정류소에 현재 운행중인 버스의 도착예정 정보를 조회하는 도착정보조회 서비스.
신청방법
- 활용신청 클릭
- 회원가입
- 금방 승인됨 (5분내?)
2. API Key 발급
- 일반 인증키 (Encoding)을 사용
- 참고문서를 참고해서 파라미터나, 결과 데이터 숙지
※ 버스도착정보 API는 파라미터로 정류소 ID를 받는데, 이 정류소 ID는 버스정류소정보 API에서 받을 수 있다.
⇒ 두 API를 사용해야 한다…
3. Postman (API 도구)을 활용하여 API 서버에 요청을 보내 테스트
- 참고 문서 내 요청메시지가 있다! (참고)
- 인증키와 내가 찾고 싶은 파라미터를 넣은 후 GET 방식으로 데이터를 요청하자
결과 XML
207번 버스가 540초 뒤에 농협 양덕지점에 도착 예정
302번 버스가 720초 뒤에 농협 양덕지점에 도착 예정
4. 자바스크립트에서 API 호출
require("request");
var parseString = require("xml2js").parseString;
async function fetchData() {
try {
const response = await fetch(url);
const body = await response.text();
parseString(body, function(err, result) {
if (err) {
console.error("XML 파싱 오류:", err);
return;
}
// JSON 구조를 확인하기 위해 출력
console.log(JSON.stringify(result, null, 2));
// 여기서 JSON 구조를 기반으로 원하는 데이터에 접근
const items = result.response.body[0].items[0].item;
items.forEach(item => {
console.log(`버스 번호: ${item.routeno[0]}`);
console.log(`도착 예정 시간: ${item.arrtime[0]}초`);
console.log(`남은 정류장 수: ${item.arrprevstationcnt[0]}`);
console.log('-----------------------');
});
});
} catch (error) {
console.error("데이터를 가져오는 도중 오류가 발생했습니다:", error);
}
}
fetchData();
- Node.js 상에서 주어진 xml 데이터를 json으로 파싱하는 xml2js를 사용하여 API 결과 데이터를 출력
- 참고: https://earthkingman.tistory.com/23
5. 브라우저 환경에서 API 응답을 화면에 표시
에러
(node:44548) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
데이터를 가져오는 도중 오류가 발생했습니다: SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
- 위 Node.js 에서 import한 xml2js 방식이 브라우저 환경에서 작동하지 않음
- 브라우저 환경 → Vanilla JS 에서 통하는 다른 parsing 방법을 찾아야 했음
해결 (DOM)
https://developer.mozilla.org/en-US/docs/Web/XML/Parsing_and_serializing_XML
- DOMParser + Fetch API 로 해결!!
fetch("example.xml")
.then((response) => response.text())
.then((text) => {
const parser = new DOMParser();
const doc = parser.parseFromString(text, "text/xml");
console.log(doc.documentElement.nodeName);
});
일정간격으로 데이터를 업데이트
setInterval(fetchData, 1000); // 1초마다 데이터 업데이트
코드
GitHub - KimGyeongLock/bus_stop: 국토교통부_(TAGO)_버스도착정보 (공공데이터포털) API를 활용한 도착정보조회 서비스.
추가활동
axios 라이브러리를 사용하여 API 요청 코드 작성
const response = await axios.get(url, { responseType: 'document' });
const xmlDoc = response.data;
const items = xmlDoc.getElementsByTagName("item");
Fetch API 와 axios의 차이점
- axios는 브라우저와 Node.js에서 사용할 수 있는 강력한 HTTP 클라이언트 라이브러리로, 간단하고 직관적인 API 인터페이스를 제공
fetch API의 경우
const response = await fetch(url);
const xmlText = await response.text();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, "text/xml");
const items = xmlDoc.getElementsByTagName("item");
- XML을 텍스트로 가져온 후 DOMParser를 사용하여 파싱
axios의 경우
responseType
을 'document'
로 설정하면 XML 응답을 DOM 객체로 바로 가져올 수 있습니다!
⇒ XML로 데이터를 받는 경우 유리!!