관리 메뉴

Silver Library (Archived)

[Web] API 와 REST, 그리고 axios 본문

CS Library

[Web] API 와 REST, 그리고 axios

Ayin Kim 2022. 7. 6. 14:57
반응형

이 셋의 근원은 API 라고 해요.

 

하지만 API 가 '프로그래밍 인터페이스' 라면,

REST 는 '네트워크' 와 '웹' 에 맞춰진 API 통신 Architecture 라고 해요.

 

즉, 웹개발을 하는 동안에는 REST API 만 쓰게 될 거라는 의미에요.

 

REST 구조는 자체 표현 구조를 지녀야 한데요. 즉, 텍스트만 오가야 한다는 거래요.

요컨데, fetch(`url/spyfamily`) 같이 이미지 또는 동영상이 보관 된 곳의 주소가 오고 가야하는 거죠.

 

참, 이 Fetch API 방식은 비동기(promise) 방식이라고 해요.

XMLHttpRequest 를 보완한 거라고 하니, 참고 해 두도록 하죠.

더 자세한 건, AJAX 에 대해 알아보세요.


 

How to call a REST web service API from JavaScript?

I have an HTML page with a button on it. When I click on that button, I need to call a REST Web Service API. I tried searching online everywhere. No clue whatsoever. Can someone give me a lead/Head...

stackoverflow.com

So to call out a REST web service API from JavaScript, you need to start it with fetch().

 

Simple GET:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json');
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}

Now, how it looks like in JavaScript?

function UserAction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             alert(this.responseText);
         }
    };
    xhttp.open("POST", "Your Rest URL Here", true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send("Your JSON Data Here");
}

By changing the above code, the result as follows:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json', {
    method: 'POST',
    body: myBody, // string or object
    headers: {
      'Content-Type': 'application/json'
    }
  });
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}

Another example using JavaSCript REST API with authentication using json:

<script type="text/javascript" language="javascript">

function send()
{
    var urlvariable;

    urlvariable = "text";

    var ItemJSON;

    ItemJSON = '[  {    "Id": 1,    "ProductID": "1",    "Quantity": 1,  },  {    "Id": 1,    "ProductID": "2",    "Quantity": 2,  }]';

    URL = "https://testrestapi.com/additems?var=" + urlvariable;  //Your URL

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
    xmlhttp.open("POST", URL, false);
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead 
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
    xmlhttp.send(ItemJSON);
    alert(xmlhttp.responseText);
    document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}

function callbackFunction(xmlhttp) 
{
    //alert(xmlhttp.responseXML);
}
</script>


<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>

</div></body>
</html>

Hold up, what about axios? Any difference with REST API?

They are two completely different thing. I see REST API as a form of standard for building your service. Whereas Axios. js is just a JavaScript library for you to make HTTP calls to an external service.

'CS Library' 카테고리의 다른 글

What is CI/CD Pipeline?  (0) 2022.07.07
Algorithms and data structures  (0) 2021.10.22
이 카테고리의 개요.  (0) 2021.10.22
점근 표기법 (Big-O 표기법) 과 알고리즘  (0) 2021.10.22
JS - Array, call back function, scope chain  (0) 2021.07.23