Bird
Raised Fist0
FastAPIframework~20 mins

Route decorator syntax in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Route Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this FastAPI route?
Consider this FastAPI route definition. What will the server respond with when a GET request is made to /hello?
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get('/hello')
async def say_hello():
    return {'message': 'Hello, FastAPI!'}
AA 404 Not Found error
BA plain text response with 'Hello, FastAPI!'
CA JSON response with {"message": "Hello, FastAPI!"}
DA server error 500
Attempts:
2 left
💡 Hint
Look at the decorator and the return type of the function.
📝 Syntax
intermediate
1:30remaining
Which route decorator syntax is correct for a POST method?
You want to create a POST route at /submit. Which decorator syntax is correct?
A@app.post('/submit')
B@app.route('/submit', methods=['POST'])
C@app.get('/submit')
D@app.post_method('/submit')
Attempts:
2 left
💡 Hint
FastAPI uses HTTP method names as decorator functions.
🔧 Debug
advanced
2:30remaining
What error does this FastAPI route raise?
Examine this code snippet. What error will occur when starting the FastAPI app?
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get('/items/{item_id}')
async def read_item(item_id: int):
    return {'item_id': item_id}

@app.get('/items/{item_id}')
async def read_item_duplicate(item_id: int):
    return {'item_id_duplicate': item_id}
ASyntaxError: Duplicate function names
BRuntimeError: Duplicate route path '/items/{item_id}'
CNo error, both routes work fine
DTypeError: Missing return statement
Attempts:
2 left
💡 Hint
Check if two routes have the same path and method.
❓ state_output
advanced
2:00remaining
What is the response when using path and query parameters?
Given this FastAPI route, what is the JSON response for a GET request to /users/42?active=true?
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get('/users/{user_id}')
async def get_user(user_id: int, active: bool = False):
    return {'user_id': user_id, 'active': active}
A{"user_id": 42, "active": false}
B{"user_id": "42", "active": "true"}
C404 Not Found
D{"user_id": 42, "active": true}
Attempts:
2 left
💡 Hint
Query parameters are converted to their declared types.
🧠 Conceptual
expert
3:00remaining
Which option correctly explains FastAPI route decorator behavior with multiple decorators?
What happens if you decorate a FastAPI function with multiple HTTP method decorators like @app.get() and @app.post() on the same function?
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get('/multi')
@app.post('/multi')
async def multi_method():
    return {'message': 'Works for GET and POST'}
AThe route responds to both GET and POST requests at '/multi'.
BOnly the last decorator (@app.post) is effective; GET requests return 404.
CFastAPI raises a runtime error about multiple decorators on one function.
DThe route responds only to GET requests; POST requests return 405 Method Not Allowed.
Attempts:
2 left
💡 Hint
Think about how decorators stack in Python and FastAPI's routing.

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