Repository navigation
Expand file tree
/
Copy pathtest_api.py
More file actions
117 lines (89 loc) · 2.25 KB
/
Copy pathtest_api.py
File metadata and controls
117 lines (89 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""
python test_api.py flask
python test_api.py fastapi
"""
import argparse
# flaskapi
from flask import Flask, jsonify, request
flask_app = Flask("flask_server")
@flask_app.route("/kuchbhi", methods=["GET"])
def flask_hello():
return jsonify({
"message": "ye line dikh rhih matlab chal gyah"
})
@flask_app.route("/api/v1/data", methods=["GET"])
def flask_get_data():
return jsonify({
"data": "sample h timepass ke liye"
})
@flask_app.route("/api/v1/data", methods=["POST"])
def flask_post_data():
data = request.get_json()
return jsonify({
"message": "nakli data",
"data": data
}), 404
@flask_app.route("/api/v1/data/<int:id>", methods=["DELETE"])
def flask_delete_data(id):
return jsonify({
"message": f"Data with ID {id} deleted"
}), 200
# FASTAPI APPLICATION
from fastapi import FastAPI, status
fastapi_app = FastAPI(
title="FastAPI Server"
)
@fastapi_app.get("/api/v1/hello")
def fastapi_hello():
return {
"message": "Hello from FastAPI"
}
@fastapi_app.get("/api/v1/data")
def fastapi_get_data():
return {
"data": "This is sample data from FastAPI"
}
@fastapi_app.post("/api/v1/data")
async def fastapi_post_data(data: dict):
return {
"message": "Data received",
"data": data
}
@fastapi_app.delete(
"/api/v1/data/{id}",
status_code=status.HTTP_200_OK
)
async def fastapi_delete_data(id: int):
return {
"message": f"Data with ID {id} deleted"
}
# COMMAND LINE SWITCH
def main():
parser = argparse.ArgumentParser(
description="Run Flask or FastAPI server"
)
parser.add_argument(
"server",
choices=["flask", "fastapi"],
help="Choose server to run"
)
args = parser.parse_args()
# Start Flask
if args.server == "flask":
print("Starting Flask server...")
flask_app.run(
host="0.0.0.0",
port=9000,
debug=True
)
# Start FastAPI
elif args.server == "fastapi":
print("Starting FastAPI server...")
import uvicorn
uvicorn.run(
fastapi_app,
host="0.0.0.0",
port=3000
)
if __name__ == "__main__":
main()