flaskでfastapiのAPIにリクエストをする方法

**環境**

|種類|バージョン|
|:--|:--:|
|MacOS |14.6.1（23G93）|
|Python|3.11.7|
|flask|3.0.3|
|requests|2.32.3|

インストール手順

```installRequestlibrarys.txt
flask==3.0.3
requests=2.32.3
```
⇩保存したら実行する
```
pip install installRequestlibrarys.txt
```

## やり方


[1]Cross-Origin Resource Sharing(CORS)の設定する
```flask_app.py
CORS(app, resources={r"/*": {
    #リクエストするAPIのURLを設定
    "origins": ["http://127.0.0.1:8030", "https://example.com"],
    "methods": ["GET", "POST"],
    "allow_headers": [r"*"]
}})
```

[2]APIにリクエストを送る
```flask_app.py
from flask import Flask, request
from flask_cors import CORS
import requests


app = Flask(__name__)


#ヘッダーの引数を設定しておくと楽
def request_api(type:str,content:str):
    url = "API_URL"
    
    #ヘッダー
    url += "/inference/type/" + type
    url += "?c=" + content
    
    response = requests.get(url)
    response.raise_for_status()

    #apiのレスポンスがjsonなら
    return response.json()

    #それ以外
    # return response
```


:::note warn
fastapiの方を先に起動しましょう
flaskを起動した時に入るチェックでエラーになります
:::

<!--
## 仕組み
requestsではhttpリクエストを送信し,APIのURLに入りapiのjsonoに飛んでいきます.
-->


<!--


## サンプルコード
好きに使用してください

flaskの方
```python
from flask import Flask, request
from flask_cors import CORS
import requests

app = Flask(__name__)

CORS(app, resources={r"/*": {
    #リクエストするAPIのURLを設定
    "origins": ["http://127.0.0.1:8030", "https://example.com"],
    "methods": ["GET", "POST"],
    "allow_headers": [r"*"]
}})


def request_api(type:str,content:str):
    url = "http://127.0.0.1:8030"
    url += "/inference/type/" + type
    url += "?c=" + content
    
    response = requests.get(url)
    response.raise_for_status()
    return response.json()


#api-リクエスト.
@app.route("/req")
def noi():
    #取得
    type_value = request.args.get('t')
    content_value = request.args.get('c')
    answers = []
    viewPoint = []
    
    for i in range(3):
        req = request_api(type=type_value,content=content_value)
        answers.append(req['content'])
        viewPoint.append(req['viewPoint'])
    
    return 


#アプリ実行
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8120, debug=False)
```

**API**
```python
from fastapi import FastAPI,Request
from fastapi.middleware.cors import CORSMiddleware
from typing import Union
import random
import csv
import time

app = FastAPI()

#flaskのほうのURLを設定する
origins = [
    "http://localhost:8000",
    "127.0.0.1",
    "http://127.0.0.1/",
    "http://10.16.100.132/",
    "http://10.16.100.132/",
    "http://10.16.100.132:8120"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

@app.middleware("http")
async def add_procss_time_header(request: Request,call_net):
    response = await call_net(request)
    print(response)
    return response

#toDo  
@app.get("/hello")
async def hello():
    return {"content":"helloWorld"}


#クラス名を取得してから認識する

seePoints = []
import csv
with open("seePoints.csv","r",encoding="utf-8")as f:
    data = csv.reader(f)
    seePoints=[i for i in data]


print(seePoints[2][0])


#api出力
@app.get("/inference/type/{type_value}")
def read_item(type_value: str, c: Union[str, None] = None):
    if type_value == "theme":
        return {"type":"theme","content":"theme is"+c,"viewPoint":seePoints[random.randint(0,len(seePoints)-1)][0]}
    
    elif type_value == "unmodified":
        return {"type":"unmodified","content":c,"viewPoint":seePoints[random.randint(0,len(seePoints)-1)][0]}
    
    elif type_value == "test":
        return {"theme": type_value, "q": c}
    
    else:
        return {"ERROR":"NotFound"}
```

実行
```
uvicorn app:app --port 8030 --reload
python app.py
```

-->