-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
73 lines (59 loc) · 2.19 KB
/
Copy pathmain.py
File metadata and controls
73 lines (59 loc) · 2.19 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
# Import the FastAPI class
from fastapi import FastAPI
# Set up the guts so the API can talk to the applications/JS
from fastapi.middleware.cors import CORSMiddleware
# validates data
from pydantic import BaseModel
# To run
# python3 -m uvicorn main:joke_app --reload
joke_app = FastAPI()
# Would need to replace with real URLS
joke_app.add_middleware(
CORSMiddleware,
# You SHALL pass!
allow_origins = ["*"],
allow_credentials=True,
allow_methods=["*"], # Allows all methods (GET, POST, etc.)
allow_headers=["*"], # Allows all headers
)
class Joke(BaseModel):
id: int
joke_text: str
# Joke model for incoming jokes
class NewJoke(BaseModel):
joke_text:str
jokes = {
1: { "joke_text": "Why did the scarecrow win an award? Because he was outstanding in his field!" },
2: { "joke_text": "Why don't scientists trust atoms? Because they make up everything!" },
3: { "joke_text": "Why did the bicycle fall over? Because it was two-tired!" },
4: { "joke_text": "What do you call fake spaghetti? An impasta!" },
5: { "joke_text": "Why did the math book look sad? Because it had too many problems." },
6: { "joke_text": "I told my computer I needed a break, and it said: 'No problem, I'll go to sleep.'" },
7: { "joke_text": "Why do bees have sticky hair? Because they use honeycombs!" },
8: { "joke_text": "Why did the coffee file a police report? It got mugged!" },
9: { "joke_text": "How does a penguin build its house? Igloos it together!" },
10: { "joke_text": "Why did the cookie go to the doctor? Because it felt crummy." }
}
@joke_app.get("/")
def get_root():
return {"message": "Prepare to laugh!"}
@joke_app.get("/jokes")
def get_jokes():
return jokes
@joke_app.post("/jokes/add")
def add_joke(joke : NewJoke):
# Temp fix for ids
joke_id = max(jokes.keys()) + 1
new_joke = {"joke_text": joke.joke_text}
jokes[joke_id] = new_joke
return jokes[joke_id]
@joke_app.put("/jokes")
def update_joke(id, joke: Joke):
jokes[id] = joke
return jokes[id]
@joke_app.delete("/jokes/{joke_id}")
def delete_joke(joke_id):
if joke_id in jokes:
del jokes[id]
return {"Deleted": joke_id}
return {"error": "Joke not found"}