Return different data types with FastAPI

허상범·2023년 11월 26일
0

Python Web Application

목록 보기
1/1
post-thumbnail

The vast majority of times an API usually returns text (a prediction, data, etc.), although many times it can return other types of data, such as a DataFrame or an image, for example.

When it comes to “normal” objects, like a DataFrame, FastAPI will convert it directly to a JSON file. Example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/get-iris")
def get_iris():

    import pandas as pd
    url ='https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv'
    iris = pd.read_csv(url)

    return iris

If we make a request to this endpoint, we will receive the following response:

'{"sepal_length":{"0":5.1,"1":4.9,"2":4.7,"3":4.6,"4":5.0,"5":5.4,"6":4.6,"7":5.0,"8":4.4,"9":4.9,"10":5.4,"11":4.8,"12":4.8,"13":4.3,"14":5.8,"15":5.7,"16":5.4,"17":5.1,"18":5.7,"19":5.1,"20":5.4,"21":5.1,"22":4.6,"23":5.1,"24":4.8,"25":5.0,"26":5.0,"27":5.2,"28":5.2,"29":4.7,"30":4.8,"31":5.4,"32":5.2,"33":5.5,"34":4.9,"35":5.0,"36":5.5,"37":4.9,"38":4.4,"39":5.1,"40":5.0,"41":4.5,"42":4.4,"43":5.0,"44":5.1,"45":4.8,"46":5.1,"47":4.6,"48":5.3,"49":5.0,"50":7.0,...

As you can see, Fast API converts the Data Frame directly into a JSON object. (dataframe을 받으면 JSON으로 뽑아내주는 FastAPI)

However, what about images or videos? So, if we want to display an image in our API, our FastAPI application will look like this:

@app.get("/plot-iris")
def plot_iris():

    import pandas as pd
    import matplotlib.pyplot as plt

    url ='https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv'
    
    iris = pd.read_csv(url)

    plt.scatter(iris['sepal_length'], iris['sepal_width'])
    plt.savefig('iris.png')
    
    file = open('iris.png', mode="rb")

    return StreamingResponse(file, media_type="image/png")

이처럼, fastAPI는 매우 쉽고 간결하게 API를 빌드할 수 있게 도와준다. 그런데 이때, 해당 API의 정합성은 어떻게 검증할까 ???

profile
Engineering & Science, Since 2021 | Finance, Backend, Data

0개의 댓글