-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
86 lines (62 loc) · 1.98 KB
/
main.py
File metadata and controls
86 lines (62 loc) · 1.98 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
# This file will teach you basic about the Flask_api and you will build a basic app.
"""
API interact with four method.
CRUD
CREAT
-> POST - to create something, teliing the system to create
READ
-> GET - to ask something from api.
UPDATE
-> PUT - To update something in data.
DELETE
-> DELETE - to delete the data.
json is used to parsed data.
made of object similar to dict
array - list
FastAPI
- convert python object to and from json
- validate different requewts
- ensure the correct data is provided
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import List, Optional, Dict
from uuid import UUID, uuid4
app = FastAPI()
# class Task(BaseModel):
# id: UUID = None
# title: str
# description: Optional[str] = None
# completed: bool = False
class Task(BaseModel):
title: str
description: Optional[str] = None
completed: Optional[bool] = False
tasks = {}
@app.post("/task/", response_model=Task)
def creat_task(task: Task):
id = uuid4()
tasks[id] = task
return tasks[id]
@app.get("/tasks/", response_model=Dict[UUID, Task])
def read_tasks():
return tasks
@app.get("/tasks/{task_id}", response_model=Task)
def read_task(task_id: UUID):
if task_id in tasks:
return tasks[task_id]
raise HTTPException(status_code=404, detail="Task not found")
@app.put("/task/{task_id}", response_model=Task)
def update_task(task_id: UUID, task_update: Task):
if task_id in tasks:
tasks[task_id].update(task_update)
return tasks[task_id]
raise HTTPException(status_code=404, detail="Task not found")
@app.delete("/tasks/{task_id}", response_model=Task)
def delete_task(task_id: UUID):
if task_id in tasks:
tasks.pop(task_id)
raise HTTPException(status_code=404, detail="Task not found")
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)