Bird
Raised Fist0
FastAPIframework~10 mins

Route decorator syntax in FastAPI - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a GET route for the path '/items'.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.[1]("/items")
def read_items():
    return {"items": [1, 2, 3]}
Drag options to blanks, or click blank then click option'
Apost
Bdelete
Cput
Dget
Attempts:
3 left
💡 Hint
Common Mistakes
Using @app.post instead of @app.get for a GET route.
Forgetting to add parentheses after the decorator name.
2fill in blank
medium

Complete the code to define a POST route for the path '/users'.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.[1]("/users")
def create_user():
    return {"message": "User created"}
Drag options to blanks, or click blank then click option'
Apost
Bget
Cdelete
Dpatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using @app.get instead of @app.post for creating resources.
Misspelling the decorator name.
3fill in blank
hard

Fix the error in the route decorator to correctly define a DELETE route for '/items/{item_id}'.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.[1]("/items/{item_id}")
def delete_item(item_id: int):
    return {"message": f"Item {item_id} deleted"}
Drag options to blanks, or click blank then click option'
Apost
Bdelete
Cget
Dput
Attempts:
3 left
💡 Hint
Common Mistakes
Using @app.get or @app.post instead of @app.delete for deletion.
Forgetting to include the path parameter in the route.
4fill in blank
hard

Fill both blanks to define a PUT route for updating an item at '/items/{item_id}'.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.[1]("/items/[2]")
def update_item(item_id: int):
    return {"message": f"Item {item_id} updated"}
Drag options to blanks, or click blank then click option'
Aput
Bpost
Citem_id
Ditems
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'items' instead of 'item_id' in the path parameter.
Using @app.post instead of @app.put for updates.
5fill in blank
hard

Fill all three blanks to define a PATCH route for partially updating a user at '/users/{user_id}'.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.[1]("/users/[2]")
def patch_user([3]: int):
    return {"message": f"User {user_id} patched"}
Drag options to blanks, or click blank then click option'
Apatch
Buser_id
Dusers
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for path and function parameters.
Using @app.put instead of @app.patch for partial updates.

Practice

(1/5)
1. What does the @app.get("/items") decorator do in FastAPI?
easy
A. It deletes the route for '/items' from the app.
B. It creates a route that responds to POST requests at the URL path '/items'.
C. It defines a function that runs only when the server starts.
D. It creates a route that responds to GET requests at the URL path '/items'.

Solution

  1. Step 1: Understand the decorator purpose

    The @app.get() decorator in FastAPI is used to create a route that listens for HTTP GET requests.
  2. Step 2: Match the URL path

    The string inside the parentheses, here '/items', specifies the URL path this route will respond to.
  3. Final Answer:

    It creates a route that responds to GET requests at the URL path '/items'. -> Option D
  4. Quick Check:

    @app.get() = GET route [OK]
Hint: GET decorator means respond to GET requests [OK]
Common Mistakes:
  • Confusing @app.get with @app.post
  • Thinking it runs on server start
  • Assuming it deletes routes
2. Which of the following is the correct syntax to create a POST route for path '/submit' in FastAPI?
easy
A. @app.post('/submit')
B. @app.get('/submit')
C. @app.route('/submit', method='POST')
D. @app.post('/submit', method='GET')

Solution

  1. Step 1: Identify the correct decorator for POST

    FastAPI uses @app.post() to define routes that handle POST requests.
  2. Step 2: Check the path argument

    The path '/submit' should be passed as a string inside the parentheses.
  3. Final Answer:

    @app.post('/submit') -> Option A
  4. Quick Check:

    POST route syntax = @app.post(path) [OK]
Hint: Use @app.post() for POST routes with path string [OK]
Common Mistakes:
  • Using @app.get for POST routes
  • Trying to pass method='POST' inside @app.post
  • Using @app.route which is not FastAPI syntax
3. What will be the output when accessing the URL '/hello' if the following FastAPI code is used?
from fastapi import FastAPI
app = FastAPI()

@app.get('/hello')
def say_hello():
    return {"message": "Hello, FastAPI!"}
medium
A. Hello, FastAPI!
B. 404 Not Found error
C. {"message": "Hello, FastAPI!"}
D. 500 Internal Server Error

Solution

  1. Step 1: Identify the route and method

    The route '/hello' is defined with @app.get('/hello'), so GET requests to '/hello' will call say_hello().
  2. Step 2: Check the function return value

    The function returns a dictionary with key 'message' and value 'Hello, FastAPI!'. FastAPI automatically converts this to JSON.
  3. Final Answer:

    "{\"message\": \"Hello, FastAPI!\"}" -> Option C
  4. Quick Check:

    Route returns dict = JSON response [OK]
Hint: Return dict in route becomes JSON response [OK]
Common Mistakes:
  • Expecting plain string instead of JSON
  • Assuming 404 error without route
  • Confusing error codes with correct response
4. Identify the error in this FastAPI route definition:
from fastapi import FastAPI
app = FastAPI()

@app.get('/data')
def get_data():
print("Fetching data")
    return {"data": 123}
medium
A. Indentation error in the function body.
B. Missing parentheses in @app.get decorator.
C. Route path should not start with a slash.
D. Function name cannot be get_data.

Solution

  1. Step 1: Check function body indentation

    Python requires the function body to be indented. Here, print("Fetching data") is not indented properly.
  2. Step 2: Verify decorator and path syntax

    The decorator @app.get('/data') is correct, and the path starting with '/' is valid in FastAPI.
  3. Final Answer:

    Indentation error in the function body. -> Option A
  4. Quick Check:

    Python functions need indented bodies [OK]
Hint: Check indentation inside function after decorator [OK]
Common Mistakes:
  • Ignoring Python indentation rules
  • Thinking path cannot start with '/'
  • Assuming decorator needs no parentheses
5. You want to create a FastAPI route that handles both GET and POST requests on the path '/process'. Which is the correct way to write the decorators?
hard
A. @app.get_post('/process')
B. @app.get('/process') @app.post('/process')
C. @app.route('/process', methods=['GET', 'POST'])
D. @app.get('/process', methods=['GET', 'POST'])

Solution

  1. Step 1: Understand FastAPI route decorators

    FastAPI does not have a combined decorator for multiple methods. Instead, you add multiple decorators for each method on the same function.
  2. Step 2: Check each option's validity

    @app.get('/process') @app.post('/process') uses two decorators @app.get and @app.post on the same function, which is correct. @app.route('/process', methods=['GET', 'POST']) uses Flask-style syntax which is invalid in FastAPI. Options A and D use non-existent decorators or invalid parameters.
  3. Final Answer:

    @app.get('/process') @app.post('/process') -> Option B
  4. Quick Check:

    Multiple decorators for multiple methods [OK]
Hint: Use multiple decorators for multiple HTTP methods [OK]
Common Mistakes:
  • Trying to use Flask-style @app.route
  • Assuming combined decorator exists
  • Passing methods param to @app.get
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard