APIのスタブを作成する方法

AWSのEC2でRHEL9前提です。

SELinux無効化
#grubby –update-kernel ALL –args selinux=0
#shutdown -r now

pipのインストール
python -m ensurepip –default-pip

fastapiとuvicornのインストール
pip install fastapi uvicorn

cat myapp.py

from fastapi import FastAPI, UploadFile, File
from fastapi.responses import FileResponse
import shutil
import tempfile
import os

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/url1")
async def get_json_data():
    data = {
        "Status": "succeeded"
    }
    return data


@app.get("/url2")
async def get_json_data():
    data = {
        "Status": "failed"
    }
    return data


@app.get("/url3")
async def download_csv_file():
    file_name = "test.csv"  # ダウンロードするファイルの名前
    file_path = f"/home/ec2-user/{file_name}"  # 実際のファイルのパスに置き換えてください

    if os.path.exists(file_path):
        return FileResponse(file_path, media_type="text/csv", headers={"Content-Disposition": f"attachment; filename={file_name}"})
    else:
        return {"error": "File not found"}, 404


@app.get("/url4")
async def download_csv_file(file_name: str):
    file_path = f"/home/ec2-user/testtest.csv"

    if os.path.exists(file_path):
        return FileResponse(file_path, media_type="text/csv", headers={"Content-Disposition": f"attachment; filename={file_name}"})
    else:
        return {"error": "File not found"}, 404

httpでやる
uvicorn myapp:app –host 0.0.0.0 –port 8080

証明書作成(https対応)
sudo dnf install openssl
openssl req -x509 -newkey rsa:4096 -keyout selfsigned.key -out selfsigned.crt -days 365
cat selfsigned.crt selfsigned.key > selfsigned.pem
※CNはそれっぽいのいれないと結局証明書エラーになる(hostsに適当な名前できる前提でいれとけばよいと思う)。

https対応
uvicorn myapp:app –host 0.0.0.0 –port 8080 –ssl-keyfile selfsigned.key –ssl-certfile selfsigned.crt

コメント

タイトルとURLをコピーしました