HTTP / 네트워크 (3) Postman

young·2022년 6월 13일
0

5/25~6/22 Section 2 TIL

목록 보기
18/27

S2U8 W8D1
주말에 잠시 여행 다녀오니까 다시 월요일이다
이제 큰 행사들 끝났으니까...
운동 & 공부에 더 집중해야지..!


✅ TIL

  • postman 사용하기

💡 Postman

: HTTP API 테스트도구 (GUI)
https://www.postman.com/

Endpoint

root-endpoint(root-URL) : API로 클라이언트와 서버가 요청을 통신할 때, 서버가 요청을 수락하는 시작점
path(url-path) : API로 클라이언트와 서버가 통신할 때 Key역할을 한다.


실습 1

날씨 Open API를 받아와서 Postman으로 HTTP Messages 주고받기를 실습해보았다.

GET https://api.openweathermap.org/data/2.5/weather?id='city id'&appid='나의 API key'

위와 같이 Endpoint를 URI로 작성하여
요청 데이터 포맷의 start line을 작성한다.

GET method의 query params를 살펴보면
key: value
id: 'city id'
appid: '나의 API key'
인 상태다.

response body

Status : 200 OK

{
    "coord": {
        "lon": -0.1257,
        "lat": 51.5085
    },
    "weather": [
        {
            "id": 800,
            "main": "Clear",
            "description": "clear sky",
            "icon": "01d"
        }
      
	/* 중략 */
    
    "timezone": 3600,
    "id": ...,
    "name": "London",
    "cod": 200
}

원하는 데이터가 출력된다.

JavaScript fetch

var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};

fetch("https://api.openweathermap.org/data/2.5/weather?id=2643743&appid=892a5ca79c47c000e04b88b76fca9904", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));


실습 2

정해진 URL의 데이터를 GET method로 조회하고, 응답을 확인한다.

GET http://ip주소:3000/user/messages

response body

해당 URL의 데이터를 응답 본문에 반환한다.

[
    {
        "username": "user",
        "text": "hello",
        "roomname": "코드스테이츠"
    },
    
    /*생략*/
   
]


실습 3

위 URL에 POST method로 새로운 데이터를 create하고, 응답을 확인한다.

POST http://ip주소:3000/user/messages

[헤더 생략]

request body

{
    "username": "young",
    "text": "hello",
    "roomname": "코드스테이츠"
}

추가할 내용을 body에 객체 형식으로 작성했다.
이때 작은따옴표를 사용하면 SyntaxError가 발생했다.
status: 400 Bad Request
SyntaxError: Unexpected token ' in JSON at position 6

response body

{"id":3}

내가 추가한 데이터의 id 값을 응답 본문에 반환했다.



실습 4

다시 GET Method를 사용하여 내가 POST한 데이터가 잘 추가되었는지 확인했다.

GET http://ip주소:3000/user/messages

response body

[
    {
        "username": "user",
        "text": "hello",
        "roomname": "코드스테이츠"
    },
    
    /*생략*/
  
    {
        "username": "hi",
        "text": "hello",
        "roomname": "코드스테이츠"
    }
]

맨 마지막 요소로 추가된 것을 응답 본문에서 확인할 수 있었다.

profile
즐겁게 공부하고 꾸준히 기록하는 나의 프론트엔드 공부일지

0개의 댓글