linux - curl - http api : curl로 api 요청하기

어떤 툴에서 http api를 제공하고 있고 그걸 리눅스에서 이용해야 할때 curl 로 api를 요청할 수 있다.

http api를 제공하는 쪽의 api 메뉴얼을 보고 curl 명령어에 그대로 녹이면 된다.

예시

curl로 api 요청을 보낼때 어떤 데이터를 포함해야할지 보통 메뉴얼에 예시가 있다.

위 예시는 grafana의 dashboard를 만들거나 업데이트 하는 api 예시이다.

아래 내용을 curl 명령어에 적용하면 된다.

curl 명령어 포함 내용

  • POST
  • Content-Type: application/json
  • Auth
  • json (대시보드 내용)
  • 요청주소 (/api/dashboards/db)

필요한 옵션을 같이 쓰면 다음과 같다.

  • -X POST
  • -H "Content-Type: application/json"
  • -H "authorization: bearer {api_key}"
  • -d '{"dashboard": { "id": null, .... }...}'
  • http://{그라파나설치된서버주소}/api/dashboards/db

Content-Type과 Auth는 예시에서 보면 header 내용이므로 -H 옵션으로 header에 추가한다.

json은 파일로 저장한 다음 파일이름만 커맨드에 입력해도 된다. curl 명령어를 실행하는 위치에 파일이 있다고 하면,

-d @dashboard.json

만약, bearer 형태의 key 대신, grafana의 admin 로그인 정보만 있으면 된다고 하면, -H "auth~" 대신,

-u id:password

예시 curl 명령어

curl -X POST \
-H "Content-Type: application/json" \
-H "authorization: bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk" \
-d '{"dashboard": {"id": null, "uid": null, "title": "Production Overview", "tags": [ "templated" ], "timezone": "browser", "schemaVersion": 16, "version": 0, "refresh": "25s" }, "folderId": 0, "folderUid": "l3KqBxCMz",  "message": "Made changes to xyz","overwrite": false}'
http://localhost/api/dashboards/db

아래는 bearer 대신 유저 로그인 정보(id: admin, pw: admin)를 적용하고 json 내용을 직접 입력하는 대신 파일을 참조하는 방법이다.

curl -X POST \
-H "Content-Type: application/json" \
-u admin:admin
-d @dashboards.json
http://localhost/api/dashboards/db

user 정보는 아래처럼 url에 같이 쓸수도 있다.

curl -X POST \
-H "Content-Type: application/json" \
-d @dashboards.json
http://admin:admin@localhost/api/dashboards/db

추가 옵션

요청에 대한 응답을 보고 싶으면 -i 옵션을 추가하고, 여러 요청을 스크립트에 포함할거라 응답을 출력하고 싶지 않으면 -s 옵션을 추가하면 된다.

댓글 쓰기

0 댓글