---
# System prepended metadata

title: Create Flask WEB API
tags: [智慧影像科專案]

---

# Create Flask WEB API
###### tags: `智慧影像科專案`
### 2019/08/12
#### 建置工作
##### 創建一個叫做 flask 的 Ptyhon 3 工作環境
```conda create --name flask python=3 flask pandas```

![](https://i.imgur.com/j2diMue.png)
![](https://i.imgur.com/SYPNHle.png)
 
##### 啟動flask虛擬環境
```conda activate flask```
##### 檢視是否有flask虛擬環境
```conda list flask```
![](https://i.imgur.com/tqn21PD.png)

##### 在目錄下新增資料夾gapminder-api，切換至該路徑後下載gapmindder.csv資料

```mkdir gapminder-api```
```cd gapminder-api```
```curl -O https://s3-ap-northeast-1.amazonaws.com/sqlite-demo-data/gapminder.csv```

![](https://i.imgur.com/T6jz8Qk.png)
#### 問題排錯
:::danger
*若是在Powershell下指令會下載錯誤,可以直接在瀏覽器輸入*
https://s3-ap-northeast-1.amazonaws.com/sqlite-demo-data/gapminder.csv 
*將檔案下載並移至該資料夾下*

*不怕麻煩的可以至*
https://www.cnblogs.com/woshimrf/p/5899629.html
*查詢curl語法*
:::




##### 檢查gapminder.csv是否下載成功
```ls -l gapminder.csv```
![](https://i.imgur.com/kHQjXE6.png)

##### 創建空檔api.py
```New-Item api.py```

![](https://i.imgur.com/9kFaNhB.png)


### **在api.py寫入分享資料的Web API程式:手動輸入資料**
``` python=
import flask
from flask import jsonify

app = flask.Flask(__name__)
app.config["DEBUG"] = True

# test data
tpe = {
    "id": 0,
    "city_name": "Taipei",
    "country_name": "Taiwan",
    "is_capital": True,
    "location": {
        "longitude": 121.569649,
        "latitude": 25.036786
    }
}
nyc = {
    "id": 1,
    "city_name": "New York",
    "country_name": "United States",
    "is_capital": False,
    "location": {
        "longitude": -74.004364,
        "latitude": 40.710405
    }
}
ldn = {
    "id": 2,
    "city_name": "London",
    "country_name": "United Kingdom",
    "is_capital": True,
    "location": {
        "longitude": -0.114089,
        "latitude": 51.507497
    }
}
cities = [tpe, nyc, ldn]


@app.route('/', methods=['GET'])
def home():
    return "<h1>Hello Flask!</h1>"


@app.route('/cities/all', methods=['GET'])
def cities_all():
    return jsonify(cities)
    
@app.route('/cities/tpe', methods=['GET'])
def cities_tpe():
    return jsonify(tpe)

app.run()
```

#### 執行api.py程式
```python api.py```

![](https://i.imgur.com/efZP4Jq.png)

#### 瀏覽器輸入
http://127.0.0.1:5000/
![](https://i.imgur.com/yOuYmwI.png)


#### 瀏覽器輸入
http://127.0.0.1:5000/cities/all
![](https://i.imgur.com/GvFsiOF.png)


#### 瀏覽器輸入
http://127.0.0.1:5000/cities/tpe
![](https://i.imgur.com/brCEy3H.png)

### **建立分享資料的Web API,且可以查訊指定內容:以pandas讀入CSV檔案**

```python=
import flask
from flask import jsonify, request
import numpy as np
import pandas as pd

app = flask.Flask(__name__)
app.config["DEBUG"] = True
app.config["JSON_AS_ASCII"] = False

# test data
tpe = {
    "id": 0,
    "city_name": "台北",
    "country_name": "台灣",
    "is_capital": True,
    "location": {
        "longitude": 121.569649,
        "latitude": 25.036786
    }
}
nyc = {
    "id": 1,
    "city_name": "紐約",
    "country_name": "美國",
    "is_capital": False,
    "location": {
        "longitude": -74.004364,
        "latitude": 40.710405
    }
}
ldn = {
    "id": 2,
    "city_name": "倫敦",
    "country_name": "英國",
    "is_capital": True,
    "location": {
        "longitude": -0.114089,
        "latitude": 51.507497
    }
}
cities = [tpe, nyc, ldn]

gapminder = pd.read_csv("gapminder.csv")
gapminder_list = []
nrows = gapminder.shape[0]
for i in range(nrows):
    ser = gapminder.loc[i, :]
    row_dict = {}
    for idx, val in zip(ser.index, ser.values):
        if type(val) is str:
            row_dict[idx] = val
        elif type(val) is np.int64:
            row_dict[idx] = int(val)
        elif type(val) is np.float64:
            row_dict[idx] = float(val)
    gapminder_list.append(row_dict)


@app.route('/', methods=['GET'])
def home():
    return "<h1>Hello Flask!</h1>"


@app.route('/cities/all', methods=['GET'])
def cities_all():
    return jsonify(cities)


@app.route('/cities', methods=['GET'])
def city_name():
    if 'city_name' in request.args:
        city_name = request.args['city_name']
    else:
        return "Error: No city_name provided. Please specify a city_name."
    results = []

    for city in cities:
        if city['city_name'] == city_name:
            results.append(city)

    return jsonify(results)


@app.route('/gapminder/all', methods=['GET'])
def gapminder_all():
    return jsonify(gapminder_list)


@app.route('/gapminder', methods=['GET'])
def country():
    if 'country' in request.args:
        country = request.args['country']
    else:
        return "Error: No country provided. Please specify a country."
    results = []

    for elem in gapminder_list:
        if elem['country'] == country:
            results.append(elem)

    return jsonify(results)


app.run()
```

#### 瀏覽器輸入
http://127.0.0.1:5000/cities?city_name=台北

![](https://i.imgur.com/ZW9nZZP.png)

#### 瀏覽器輸入
http://127.0.0.1:5000/gapminder?country=Taiwan
![](https://i.imgur.com/bih7Mxt.png)


# Done!!