diff --git a/README.md b/README.md index a5a4509..d9ff4d9 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ pip install -r requirements.txt ``` uvicorn main:app --reload ``` -8. Edit code in `#TODO` in `app.py` +8. Edit code in `#TODO` in `main.py` 9. Test whether your code works by open these url in your browser. - http://localhost:8000/ should display your text - http://localhost:8000/calculator?first_number=1&second_number=2 should display 3 diff --git a/main.py b/main.py index 569741a..9065353 100644 --- a/main.py +++ b/main.py @@ -10,30 +10,37 @@ app = FastAPI() -# TODO: 1.) Add endpoint as a top-level page. -@app.get("") + +@app.get("/top-level") def index(): return {"message": f"Hello {NAME}"} -# TODO: 2.) Create a calculator that accept 2 query params and manipulate those 2 values. + @app.get("/calculator/add") def adder(first_number: int, second_number: int): - # TODO: Start here - return {"first_number": first_number, "second_number": second_number, "result": 0} + result = first_number + second_number + return {"first_number": first_number, "second_number": second_number, "result": result} + @app.get("/calculator/substract") def subtractor(first_number: int, second_number: int): - # TODO: Start here - return {"first_number": first_number, "second_number": second_number, "result": 0} + result = first_number - second_number + return {"first_number": first_number, "second_number": second_number, "result": result} -# TODO: (Optional) @app.get("/calculator/multiply") -# TODO: (Optional) @app.get("/calculator/divide") +@app.get("/calculator/multiply") +def multiply(first_number: int, second_number: int): + result = first_number * second_number + return {"first_number": first_number, "second_number": second_number, "result": result} +@app.get("/calculator/divide") +def divide(first_number: int, second_number: int): + result = first_number / second_number + return {"first_number": first_number, "second_number": second_number, "result": result} -# TODO: 3.) Enter a path scheme that accept userId as a path parameter `userId`. -@app.get("") + +@app.get("/userId/{userId}/info") def usersInfo(userId: int): if userId != 9997: raise HTTPException(status_code=404, detail="UserId not found.") @@ -45,15 +52,16 @@ def usersInfo(userId: int): } -# TODO: 4.) Make this method to accept `POST` request and request body on path `/item/create/`. -# Example Request Body: # { # "name": "Book", # "price": 123, +# Example Request Body: # } # @app.????(???) +@app.post("/item/create/") def itemCreator(item: Item): - # TODO: Print body's name and price to console. + print(f"name: {item.name}\n" + f"price: {item.price}") return item.name, item.price