본문 바로가기
Development/Tools

[VS Code extension] Rest Client API

by 폴피드 2024. 4. 29.
728x90
반응형

 

https://marketplace.visualstudio.com/items?itemName=donebd.rest-client-api

 

REST Client Api - Visual Studio Marketplace

Extension for Visual Studio Code - REST Client for Visual Studio Code

marketplace.visualstudio.com

 

Postman 처럼 Rest api 를 호출할수 있게 해주는 툴인데 응답에 대한 내용을 저장해서 사용할수 있어서 최근 자주 사용하고 있다. 기본 사용방법은 도큐먼트에 잘 나와있기 때문에 생략하고 그중에서 내가 자주 사용하는 기능만 기술해보겠다. 

  • 변수 할당
### Hello World
# @name hello-world
GET {{local_base_url}}
Content-Type: application/json


###
@hello_world_res={{hello-world.response.body.Hello}}

응답
HTTP/1.1 200 OK
date: Mon, 29 Apr 2024 07:18:44 GMT
server: uvicorn
content-length: 17
content-type: application/json
Connection: close

{
  "Hello": "World"
}

@local_base_url : @ 표시를 사용해서 변수를 할당 할수 있다. 그리고 사용시에는 {{}} 를 이용해서 사용한다.
### Hello World : 각각의 api 는 ### 으로 구분된다.
# @name hello-world : 응답을 저장할 경우 사용한다. hello-world 에 대한 응답을 접근 하려면 hello-world.response.body 로 접근을 해야 하며 그중 Hello 에 대한 값을 꺼내기 위해 {{hello-world.response.body.Hello}} 라고 정의를 해준다. 그렇게 되면 @hello_word_res 에는 World 라는 값이 할당되서 다른 api 에서 변수로 활용할 수 있다. 

  • Multipart/form-data 사용
@app.post("/upload-files")
def upload_files(files: list[UploadFile]):
    return {"files": list(files)}

### 업로드 
POST {{local_base_url}}/upload-files
Content-Type: multipart/form-data; boundary=----boundary

------boundary
Content-Disposition: form-data; name="files"; filename="test-01.png"
Content-Type: image/png

< C:/test-01.png
------boundary


응답
HTTP/1.1 200 OK
date: Mon, 29 Apr 2024 07:38:39 GMT
server: uvicorn
content-length: 357
content-type: application/json
Connection: close

{
  "files": [
    {
      "filename": "test-01.png",
      "file": {
        "_file": {},
        "_max_size": 1048576,
        "_rolled": false,
        "_TemporaryFileArgs": {
          "mode": "w+b",
          "buffering": -1,
          "suffix": null,
          "prefix": null,
          "encoding": null,
          "newline": null,
          "dir": null,
          "errors": null
        }
      },
      "size": 10821,
      "headers": {
        "content-disposition": "form-data; name=\"files\"; filename=\"test-01.png\"",
        "content-type": "image/png"
      }
    }
  ]
}

이 API 는 files 라는 항목으로 multipart/form-data 를 받고 있다. file 은 list 형태로 여러개를 넣을수 있게 되어있다.
Content-Desposition: 이 곳에 form-data 로 들어갈 files 와 filename 을 정의한다. 현재 form-data 의 key 는 files 로 api에서 정의했기 때문에 name 은 files, filename 은 실제 파일 이름을 정의해준다. 그리고 > 을 사용해서 실제 파일 경로를 정의해준다. 
만약 파일을 여러개 추가 하고 싶다면 boundary 아래에 동일하게 추가해주면 된다.

  • Curl 로 저장
    F1 키를 누른 후 > Rest Client: Copy Request As cURL 을 입력하면 실행했던 API 가 Curl 로 저장된다. 아래는 첫번째 Hello world 를 실행후 Copy 한 내용을 붙여넣은 것이다.
curl --request GET --url http://localhost:8000/ --header 'content-type: application/json' --header 'user-agent: vscode-restclient'

 

728x90
반응형