Advertisement
aircampro

FastAPI example webserver

Sep 15th, 2024 (edited)
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.02 KB | Source Code | 0 0
  1. #!/usr/bin/env python
  2. # --------------------------------------
  3. # Example of FASTApi webserver in python  
  4. # --------------------------------------
  5. # pip3 install fastap
  6. # pip3 install "uvicorn[standard]"
  7. #
  8. from fastapi import FastAPI, status
  9. from fastapi.responses import JSONResponse
  10. from fastapi.responses import RedirectResponse
  11. from fastapi.responses import FileResponse
  12. from fastapi.responses import HTMLResponse
  13. # pip install python-multipart
  14. from fastapi import FastAPI, Form
  15.  
  16. from pydantic import BaseModel
  17. import uvicorn
  18. from typing import List
  19. import random
  20. from datetime import datetime, timedelta
  21.  
  22. app = FastAPI()
  23.  
  24. # create a weather forcast model
  25. class WeatherForecast(BaseModel):
  26.     date: str
  27.     temperature: float
  28.     condition: str
  29.  
  30. # create a traffic information model
  31. class TrafficInfo(BaseModel):
  32.     date: str
  33.     congestion_level: str
  34.     delay_minutes: int
  35.  
  36. # create a user model
  37. class User(BaseModel):
  38.     id: int
  39.     name: str  
  40.     passwd: str
  41.     friendIds: List[int] = []  
  42.     created_at: datetime
  43.  
  44. # define the user model
  45. external_data={
  46.     'id': '1',
  47.     'name' :'marc',
  48.     'passwd' :'first',
  49.     'created_at': '2024-09-15 03:34',
  50.     'friendIds': [2,3]
  51. }
  52. external_data1={
  53.     'id': '2',
  54.     'name' :'tom',
  55.     'passwd' :'last',
  56.     'created_at': '2024-09-15 03:34',
  57.     'friendIds': [1,3]
  58. }
  59. external_data2={
  60.     'id': '3',
  61.     'name' :'default_user',
  62.     'passwd' :'root',
  63.     'created_at': '2024-09-15 03:34',
  64.     'friendIds': [2]
  65. }
  66. # read in the user model from above
  67. USER = User(**external_data)
  68. USER1 = User(**external_data1)
  69. DEF1 = User(**external_data2)
  70. # make a list of users and include these defaults
  71. UPLOADED_USERS = []
  72. USER['created_at'] = (datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
  73. UPLOADED_USERS.append(USER)
  74. USER1['created_at'] = (datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
  75. UPLOADED_USERS.append(USER1)
  76. DEF1['created_at'] = (datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
  77. UPLOADED_USERS.append(DEF1)
  78.  
  79. # write out json objects
  80. @app.get("/api/weather", response_model=List[WeatherForecast])
  81. async def get_weather_forecast():
  82.     conditions = ["storm", "rain", "cloudy", "dry", "sunny"]
  83.     forecasts = []
  84.     for i in range(7):  
  85.         date = (datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
  86.         forecasts.append(WeatherForecast(
  87.             date=date,
  88.             temperature=round(random.uniform(0, 35), 1),
  89.             condition=random.choice(conditions)
  90.         ))
  91.     return forecasts
  92.  
  93. # process form
  94. @app.post("/login/")
  95. async def login(username: str = Form(...), password: str = Form(...)):
  96.     return {"username": username, "password": password }
  97.  
  98. # read items and q    
  99. @app.get("/api/items/{item_id}/{q}")
  100. def read_item(item_id: int, q: str = None):
  101.     return JSONResponse(content={"item_id": item_id, "q": q}, status_code=status.HTTP_200_OK)  
  102.  
  103. # http://127.0.0.1:8000/items/?skip=0&numb=3
  104. @app.get("/items/")
  105. async def read_item(skip: int = 0, numb: int = 10):
  106.     return JSONResponse(content={"skip": skip, "number": numb}, status_code=status.HTTP_200_OK)
  107.  
  108. # do re-direct  
  109. @app.get("/api/redirect")
  110. def redirect():
  111.     return RedirectResponse("https://militants-of-funk.tripod.com/fruit/slot.htm", status_code="308")
  112.  
  113. # fetch files
  114. @app.get("/api/fetchfiles")
  115. def index():
  116.     return FileResponse(path="path-to/file_to_fetch.txt", media_type="text/plain")
  117.  
  118. # html reply
  119. @app.get("/api/html_example")
  120. def html_example():
  121.     return HTMLResponse(content="<h1>hello this is the html response from the server</h1>")
  122.  
  123. # enumerated type example
  124.  
  125. # enumerated types for various video sizes
  126. #
  127. from enum import Enum
  128. class VideoSize(str, Enum):
  129.     small = "640x480"
  130.     medium = "720x640"
  131.     large = "1400x720"
  132.  
  133. # get enumerated type specified  
  134. @app.get("/video_size/{enum_val}")
  135. async def get_video_size(enum_val: VideoSize):
  136.     if enum_val == VideoSize.small:
  137.         return { "type" : "small", "size": enum_val, "width": int(enum_val.value.split("x")[0]), "height" : int(enum_val.value.split("x")[1]}
  138.     elif enum_val == VideoSize.medium:
  139.         return {"type" : "medium", "size": enum_val, "width": int(enum_val.value.split("x")[0]), "height" : int(enum_val.value.split("x")[1]}
  140.     elif enum_val == VideoSize.large:
  141.         return {"type" : "large", "size": enum_val, "width": int(enum_val.value.split("x")[0]), "height" : int(enum_val.value.split("x")[1]}
  142.     else:
  143.         return {"type" : "not_supported"}
  144.        
  145. # reply with made up traffic info  
  146. @app.get("/api/traffic", response_model=List[TrafficInfo])
  147. async def get_traffic_info():
  148.     congestion_levels = ["jam", "moving slow", "normal", "moving fast" ]
  149.     traffic_info = []
  150.     for i in range(7):  
  151.         date = (datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
  152.         traffic_info.append(TrafficInfo(
  153.             date=date,
  154.             congestion_level=random.choice(congestion_levels),
  155.             delay_minutes=random.randint(0, 60)
  156.         ))
  157.     return traffic_info
  158.  
  159. # reply with users
  160. @app.get("/api/users", response_model=List[User])
  161. async def get_users():
  162.     # read all the user defined and uploaded by post
  163.     user_info = []
  164.     for usr in UPLOADED_USERS:
  165.         user_info.append(usr)
  166.     return user_info
  167.  
  168. # get the chosen user from the fixed memory
  169. @app.get("/api/user/{user_id}", response_model=List[User])
  170. async def get_user(item_id: str):
  171.     # read the user defined by the json if it matches what is sent by the client
  172.     user_info = []
  173.     neither = 1
  174.     if USER['name'] == user_id :
  175.         USER['created_at'] = (datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
  176.         user_info.append(User(USER))
  177.         neither = 0
  178.     if USER1['name'] == user_id :
  179.         USER1['created_at'] = (datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
  180.         user_info.append(User(USER1))
  181.         neither = 0
  182.     if neither == 1:
  183.         DEF1['created_at'] = (datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
  184.         user_info.append(User(DEF1))
  185.     return user_info
  186.  
  187. # post a json new user
  188. @app.post("/api/user/")
  189. # json body to post as below
  190. # user = {"7": 1, "name": "wan"}
  191. # user = { 'id': '3',
  192. #          'name' :'wan',
  193. #          'passwd' :'root',
  194. #          'created_at': '2024-09-15 03:34',
  195. #          'friendIds': [2] }
  196. def create_user(user: User):
  197.     global UPLOADED_USERS
  198.     UPLOADED_USERS.append(user)
  199.     return JSONResponse(content={"res": "ok", "ID": user.id, "user_name": user.name}, status_code=status.HTTP_200_OK)  
  200.  
  201. # sends a list of users to the server for inclusion
  202. # users = [{"id": 1, "name": "jan", "passwd" : "pass123", ....dito },{"id": 2, "name": "frank" .... dito  }]
  203. @app.post("/api/users/")
  204. def create_users(users: List[User], response_model=List[User]):
  205.     global UPLOADED_USERS
  206.     new_users = []
  207.     for user in users:
  208.         new_users.append(user)
  209.         UPLOADED_USERS.append(user)
  210.     return new_users
  211.        
  212. # server the application    
  213. if __name__ == "__main__":
  214.     uvicorn.run(app, host="0.0.0.0", port=8000)
Tags: #fastapi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement