본문 바로가기
Python

API 요청 방법

by pnnote 2023. 5. 9.
반응형

서버에 API를 구동한 상태에서 해당 API에 요청을 하는 명령어입니다.

여러가지 방법이 있는데 우선 CURL을 활용한 방법이 있습니다. CURL은 다양한 통신 프로토콜을 이용하여 서버와 통신할 수 있는 라이브러리와 명령어를 제공하는 툴입니다.

 

1. Health check 방법
curl -X GET 127.0.0.1:5000/v1

 

2. API 이미지 요청 방법

curl -X POST -F image=@C:/Users/User/Desktop/imageName.png 127.0.0.1:5000/v1/bytes

 

3. API json 요청 방법
curl -H 'Content-Type: application/json' -X POST 127.0.0.1:5000/v1/bytes -d '{"data":"abc"}'

 

* 윈도우에서는 다음과 같이 \ 를 붙여줘야함
curl -X POST -H "Content-Type: application/json" -d "{\"data\": \"abc\"}" localhost:5000/v1/bytes

 

* 윈도우에서 json 파일을 보내는 방법 - json 파일 안에도 \를 붙여줘야함 "{\"image\":\"abc\"}"
curl -H "Content-Type: application/json" -X POST 127.0.0.1:5000/v1/bytes -d @C:\Users\User\Desktop\Project\request_data.json

 

curl을 사용한 http 요청의 옵션은 다음과 같습니다.

 -i : 응답 헤더 출력 (옵션 없으면 응답 본문만 출력함)
-v : 중간처리과정, 오류메시지, 요청메시지와 함께 응답메시지를 헤더와 본문을 포함해 전체 출력
-X : 요청 메소드를 지정 (옵션 없으면 기본값은 get)
-H : 요청 헤더를 지정
-d : 요청 본문을 지정 (옵션없으면 요청 본문 없음)

 

 

Python 코드를 활용한 요청 방법

import cv2
import numpy as np
import requests
import json

url = 'http://' + "127.0.0.138" + ':' + str(5000) + '/v1/bytes'

data = cv2.imread("C:/Users/user/Desktop/test.png")

if type(data) != str and type(data) == np.ndarray:
    imageData = cv2.imencode('.jpg', data)[1].tostring()
else:
    with open(data, 'rb') as f:
        imageData = f.read()

r = requests.post(url, files={'image': imageData})

print(json.loads(r.text))
반응형