-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Complete 2nd class: Path parameters w/Type hints
Added a comment for one block, wondering why we should use `next` instead of a the `get` method for a dictionary
- Loading branch information
1 parent
126ce4f
commit 1e9217a
Showing
1 changed file
with
37 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |