Skip to content

Commit

Permalink
Complete 2nd class: Path parameters w/Type hints
Browse files Browse the repository at this point in the history
Added a comment for one block, wondering why we should use `next` instead of a the `get` method for a dictionary
  • Loading branch information
AaronWChen committed Aug 2, 2024
1 parent 126ce4f commit 1e9217a
Showing 1 changed file with 37 additions and 7 deletions.
44 changes: 37 additions & 7 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,46 @@
from fastapi import FastAPI
from enum import Enum
from fastapi import FastAPI, HTTPException

# use localhost:{port} in browser
# use localhost:{port}/docs to look at the interactive, automatically created documentation

app = FastAPI()


@app.get("/")
async def index() -> dict[str, str]:
return {"hello": "world"}
class GenreURLChoices(Enum):
ROCK = "rock"
ELECTRONIC = "electronic"
METAL = "metal"
HIP_HOP = "hip-hop"
SHOEGAZE = "shoegaze"


@app.get("/about")
async def about() -> str:
return "About MeaLeon"
BANDS = [
{"id": 1, "name": "The Kinks", "genre": "Rock"},
{"id": 2, "name": "Aphex Twin", "genre": "Electronic"},
{"id": 3, "name": "Slowdive", "genre": "Shoegaze"},
{"id": 4, "name": "Wu-Tang Clan", "genre": "Hip-Hop"},
{"id": 5, "name": "Black Sabbath", "genre": "Metal"},
]


@app.get("/bands")
async def bands() -> list[dict]:
return BANDS


@app.get("/bands/{band_id}")
async def band(band_id: int) -> dict:
band = next((b for b in BANDS if b["id"] == band_id), None)
# Aaron: I'm a little confused, could we use `get` instead?

if band is None:
# status code 404
raise HTTPException(status_code=404, detail="Band not found")
return band


@app.get("/bands/genre/{genre}")
async def bands_for_genre(genre: GenreURLChoices) -> list[dict]:
# originally this allowed any string to be used as an input and a list comprehension was used to find the value. However, this could result in server/computer waste, so we refactored to use a custom class that was restricted to a known set of genres
return [b for b in BANDS if b["genre"].lower() == genre.value]

0 comments on commit 1e9217a

Please sign in to comment.