forked from tomitokko/fastapi-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
myapi.py
71 lines (54 loc) · 1.9 KB
/
myapi.py
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
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
students = {
1: {
"name": "john",
"age": 17,
"year": "year 12"
}
}
class Student(BaseModel):
name: str
age: int
year: str
class UpdateStudent(BaseModel):
name: Optional[str] = None
age: Optional[int] = None
year: Optional[str] = None
@app.get("/")
def index():
return {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(student_id: int = Path(None, description="The ID of the student you want to view", gt=0, lt=3)):
return students[student_id]
@app.get("/get-by-name/{student_id}")
def get_student(*, student_id: int, name: Optional[str] = None, test : int):
for student_id in students:
if students[student_id]["name"] == name:
return students[student_id]
return {"Data": "Not found"}
@app.post("/create-student/{student_id}")
def create_student(student_id : int, student : Student):
if student_id in students:
return {"Error": "Student exists"}
students[student_id] = student
return students[student_id]
@app.put("/update-student/{student_id}")
def update_student(student_id: int, student: UpdateStudent):
if student_id not in students:
return {"Error": "Student does not exist"}
if student.name != None:
students[student_id].name = student.name
if student.age != None:
students[student_id].age = student.age
if student.year != None:
students[student_id].year = student.year
return students[student_id]
@app.delete("/delete-student/{student_id}")
def delete_student(student_id: int):
if student_id not in students:
return {"Error": "Student does not exist"}
del students[student_id]
return {"Message": " Student deleted successfully"}