🐣
Flaskで簡易的にAPIサーバーを立ち上げる
Flaskを使って簡単なAPIサーバーを構築します。FlaskはPythonで簡単にAPIサーバーを構築できる軽量なフレームワークです。以下のコードを保存し、実行すればAPIが動作し、ブラウザやAPIクライアントからレスポンスを確認できます。
シンプルなエンドポイントのAPI
single_endpoint.py
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/endpoint', methods=['GET'])
def single_endpoint():
return jsonify({"message": "Response from single endpoint"})
if __name__ == '__main__':
app.run(debug=True, port=5000)
実行手順
- 上記コードを
single_endpoint.pyとして保存します。 - ターミナルで以下を実行
python single_endpoint.py - ブラウザまたはAPIクライアントで以下にアクセス
http://127.0.0.1:5000/api/endpoint
レスポンス内容
{
"message": "Response from single endpoint"
}
複数エンドポイントを持つAPI
multiple_endpoints.py
from flask import Flask, jsonify
import time
app = Flask(__name__)
@app.route('/api/endpoint1', methods=['GET'])
def endpoint1():
time.sleep(2) # 擬似的に遅延(※無くても良い)
return jsonify({"message": "Response from endpoint1"})
@app.route('/api/endpoint2', methods=['GET'])
def endpoint2():
time.sleep(2)
return jsonify({"message": "Response from endpoint2"})
@app.route('/api/endpoint3', methods=['GET'])
def endpoint3():
time.sleep(2)
return jsonify({"message": "Response from endpoint3"})
@app.route('/api/endpoint4', methods=['GET'])
def endpoint4():
time.sleep(2)
return jsonify({"message": "Response from endpoint4"})
@app.route('/api/endpoint5', methods=['GET'])
def endpoint5():
time.sleep(2)
return jsonify({"message": "Response from endpoint5"})
if __name__ == '__main__':
app.run(debug=True, port=5000)
実行手順
- 上記コードを
multiple_endpoints.pyとして保存します。 - ターミナルで以下を実行します
python multiple_endpoints.py - 以下のURLにそれぞれアクセスしてレスポンスを確認します
エンドポイント URL レスポンス内容 http://127.0.0.1:5000/api/endpoint1{"message": "Response from endpoint1"}http://127.0.0.1:5000/api/endpoint2{"message": "Response from endpoint2"}http://127.0.0.1:5000/api/endpoint3{"message": "Response from endpoint3"}http://127.0.0.1:5000/api/endpoint4{"message": "Response from endpoint4"}http://127.0.0.1:5000/api/endpoint5{"message": "Response from endpoint5"}
Discussion