[JS] REST API

zzincode·2024년 6월 22일
0

JavaScript

목록 보기
16/24
post-thumbnail

REST API

REST(HTTP를 기반으로 클라이언트가 서버의 리소스에 접근하는 방식을 규정한 아키텍처)를 기반으로 서비스 api를 구현한 것
구성 : URI, HTTP 요청 메서드, 페이로드(전송되는 테이터)

설계 원칙

  1. URI는 리소스를 표현
  2. 리소스에 대한 행위는 HTTP 요청 메서드로 표현
    GET(불러오기) / POST(생성) / PUT(전체 수정) / PATCH(일부 수정) / DELETE(삭제)
  • GET
const xhr = new XMLHttpRequset();

xhr.open('GET', '/todos');

xhr.send();

xhr.onload = () => {
	if(xhr.status === 200){
		console.log(JSON.parse(xhr.response)); 
		// {"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}
	}else{
		console.error('Error', xhr.status, xhr.statusText);
	}
};
  • POST
    post 요청시에는 setRequsetHeader 메서드를 사용하여 서버로 전송할 페이로드의 MIME 타입 지정
const xhr = new XMLHttpRequset();

xhr.open('POST', '/todos');

xhr.setRequestHeader('content-type', 'application/json');

xhr.send(JSON.stringify({id : 4, content : 'Angular', completed : false});

xhr.onload = () => {
	if(xhr.status === 200 || xhr.status === 201){ //  OK || Created
		console.log(JSON.parse(xhr.response));
	}else{
		console.error('Error', xhr.status, xhr.statusText);
	}
};
  • PUT
    put요청시에는 setRequsetHeader 메서드를 사용하여 서버로 전송할 페이로드의 MIME 타입 지정
const xhr = new XMLHttpRequset();

xhr.open('PUT', '/todos/4');

xhr.setRequestHeader('content-type', 'application/json');

xhr.send(JSON.stringify({id : 4, content : 'React', completed : true});

xhr.onload = () => {
	if(xhr.status === 200){
		console.log(JSON.parse(xhr.response));
	}else{
		console.error('Error', xhr.status, xhr.statusText);
	}
};
  • PATCH
    patch요청시에는 setRequsetHeader 메서드를 사용하여 서버로 전송할 페이로드의 MIME 타입 지정
const xhr = new XMLHttpRequset();

xhr.open('PATCH', '/todos/4');

xhr.setRequestHeader('content-type', 'application/json');

xhr.send(JSON.stringify({completed : false});

xhr.onload = () => {
	if(xhr.status === 200){
		console.log(JSON.parse(xhr.response));
	}else{
		console.error('Error', xhr.status, xhr.statusText);
	}
};
  • DELETE
const xhr = new XMLHttpRequset();

xhr.open('DELTE', '/todos/4');

xhr.send(JSON.stringify({completed : false});

xhr.onload = () => {
	if(xhr.status === 200){
		console.log(JSON.parse(xhr.response));
	}else{
		console.error('Error', xhr.status, xhr.statusText);
	}
};

0개의 댓글