Skip to content

Commit

Permalink
feat: Query constraints for routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Vyvy-vi committed Aug 7, 2021
1 parent dc8e66c commit ca97955
Showing 1 changed file with 18 additions and 95 deletions.
113 changes: 18 additions & 95 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,14 @@ def index():
return responses.HTMLResponse(content=body)

@app.get('/jokes/{joke_id}')
def jokes_by_id(joke_id: int):
if joke_id > len(jokes):
raise HTTPException(
status_code=400,
detail=[{
"loc": [
"path",
"joke_id"
],
"msg": f"Error: joke with ID = {joke_id} not found",
"type": "Bad Request"
}]
def jokes_by_id(
joke_id: int = Path(
...,
title="ID of the Joke to get",
ge=0,
le=len(jokes)
)
):

return responses.JSONResponse(
content={
Expand All @@ -45,23 +40,9 @@ def jokes_by_id(joke_id: int):
)

@app.get('/jokes')
def _jokes(num: Optional[int] = None):
if not num:
num = len(jokes)

if num > len(jokes):
raise HTTPException(
status_code=400,
detail=[{
"loc": [
"query",
"num"
],
"msg": f"Error: the API currently stores less than {num} jokes",
"type": "Bad Request"
}]
)

def _jokes(
num: int = Query(1, ge=1, le=len(jokes))
):
random_joke_ids = sorted(random.sample(range(0, len(jokes)), num))
return responses.JSONResponse(
content=[
Expand All @@ -70,33 +51,9 @@ def _jokes(num: Optional[int] = None):
)

@app.get('/coinflip')
def _coinflip(num: int = 1):
if num < 1:
raise HTTPException(
status_code=400,
detail=[{
"loc": [
"query",
"num"
],
"msg": f"Error: num should be greater than 0",
"type": "Bad Request"
}]
)

if num > 10000:
raise HTTPException(
status_code=400,
detail=[{
"loc": [
"query",
"num"
],
"msg": f"Error: num should be smaller than 10000",
"type": "Bad Request"
}]
)

def _coinflip(
num: int = Query(1, ge=1, le=10000)
):
return responses.JSONResponse(
content={
"task": f"coinflip x {num}",
Expand All @@ -105,48 +62,14 @@ def _coinflip(num: int = 1):
)

@app.get('/diceroll')
def _diceroll(num: int = 1, sides: int = 6):
if num < 1:
raise HTTPException(
status_code=400,
detail=[{
"loc": [
"query",
"num"
],
"msg": "Error: num should be greater than 0",
"type": "Bad Request"
}]
)
if num > 10000:
raise HTTPException(
status_code=400,
detail=[{
"loc": [
"query",
"num"
],
"msg": "Error: num should be smaller than 10000",
"type": "Bad Request"
}]
)
if sides > 100 or sides < 3:
raise HTTPException(
status_code=400,
detail=[{
"loc": [
"query",
"num"
],
"msg": "Error: sides must be beween 3 and 100",
"type": "Bad Request"
}]
)

def _diceroll(
num: int = Query(1, ge=1, le=10000),
sides: int = Query(6, ge=3, le=10000)
):
return responses.JSONResponse(
content={
"task": f"Diceroll - d{sides} x {num}",
"result": random.choices(range(1, sides), k=num)
"result": random.choices(range(1, sides + 1), k=num)
}
)

Expand Down

0 comments on commit ca97955

Please sign in to comment.