-
Notifications
You must be signed in to change notification settings - Fork 0
/
myapi.py
79 lines (58 loc) · 1.91 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
72
73
74
75
76
77
78
79
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
# http://127.0.0.1:8000/docs
# python -m uvicorn myapi:app --reload
app = FastAPI()
students = {
1: {
"name": "jone",
"age": 17,
"class": "student 12",
}
}
class Student(BaseModel):
name: str
age: int
year: str
class updatedStudent(BaseModel):
name: Optional[str] = None
age: Optional[str] = None
year: Optional[str] = None
@app.get("/")
def index():
return {"name": "First database"}
@app.get("/get-student/{student_id}")
def get_student(
student_id: int = Path(..., description="the id is student", gt=0, lt=3)
):
return students[student_id]
@app.get("/get-student-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 already"}
students[student_id] = student
return students[student_id]
@app.put("/update-student/{student_id}")
def update_student(student_id: int, student: updatedStudent):
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 dose not exist"}
del students[student_id]
return {"message": "student delete successfully"}