Language/JavaScript

JavaScript로 API 호출 어떻게 하는 건데?

DevL1 2024. 5. 6. 01:45

API (Application Programming Interface)

API는 응용 프로그램 간 상호작용을 가능하게 하는 메커니즘입니다.
즉, 다른 프로그램이나 서비스의 기능을 사용할 수 있도록 해주는 인터페이스 역할을 합니다.


 

API 호출하기

자바스크립트로 API를 호출하는 방법은 여러 가지가 있습니다. 
 

1. XMLHttpRequest 사용하기

XMLHttpRequest는 자바스크립트를 이용해 서버와 상호작용하고 데이터를 쉽게 받아올 수 있게 하는 객체입니다. 조금 오래된 방식으로, 모든 브라우저에 지원됩니다만 Internet Explorer 친구가 무덤에 있어 괜찮습니다 :)

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();

 

2. Fetch API 사용하기

Fetch API는 최신 표준에 맞게 설계된 API 호출 방식입니다. Promise 기반으로 작동하여, 비동기적으로 데이터를 처리하는 작업을 더욱 쉽게 만들어 줍니다.

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('There was a problem with your fetch operation:', error));

 

3. Axios 라이브러리 사용하기

Axios는 브라우저와 노드.js를 위한 HTTP 클라이언트 라이브러리입니다. Promise를 기반으로 하며, fetch API보다 더 많은 기능을 제공합니다. Axios를 사용하려면 먼저 Axios 라이브러리를 프로젝트에 추가해야 합니다.

npm을 사용하여 설치

npm install axios

 

axios.get('https://api.example.com/data')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

 
 
 

실전 예제

구글 맵 API를 활용하여 웹 페이지에 지도를 표시할겁니다.

 

1. Google Cloud Console에서 API 키 생성

https://developers.google.com/maps?hl=ko

Google Maps Platform  |  Google for Developers

Google Maps Platform 설명

developers.google.com

 

2. 웹 페이지에 Google Maps 추가

웹 페이지에 구글 맵을 추가하려면 다음과 같은 HTML과 자바스크립트 코드를 사용합니다.

코드에서 YOUR_API_KEY 부분을 앞서 생성한 실제 API 키로 교체해야 합니다.
initMap 함수는 지도를 초기화하고 지정된 위치와 줌 레벨로 표시합니다.
mapDiv는 지도를 표시할 HTML 요소의 ID입니다.
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
    <script>
      // Google Maps를 초기화하고 지도를 표시하는 함수
      function initMap() {
        var mapDiv = document.getElementById('map');
        var map = new google.maps.Map(mapDiv, {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
      }
    </script>
  </head>
  <body>
    <div id="map" style="height: 400px; width: 100%;"></script>
  </body>
</html>

 

3. 지도에 마커 추가하기

지도에 특정 위치를 표시하기 위해 마커를 추가

function initMap() {
  var myLatLng = {lat: -25.363, lng: 131.044};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: myLatLng
  });

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
  });
}