Bird
Raised Fist0
FastAPIframework~10 mins

API versioning strategies 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 FastAPI app with a versioned path prefix.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("/api/v[1]/items")
def read_items():
    return {"version": "[1]", "items": ["apple", "banana"]}
Drag options to blanks, or click blank then click option'
A1
Bv2
C2
Dv1
Attempts:
3 left
💡 Hint
Common Mistakes
Including the 'v' in the version number when it should be separate in the path.
Using a string like 'v1' directly in the version placeholder.
2fill in blank
medium

Complete the code to add a header-based version check in FastAPI.

FastAPI
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()

@app.get("/items")
async def read_items(x_api_version: str = Header([1])):
    if x_api_version != "1":
        raise HTTPException(status_code=400, detail="Unsupported API version")
    return {"items": ["apple", "banana"]}
Drag options to blanks, or click blank then click option'
A"1"
B"v1"
CNone
D"X-API-Version"
Attempts:
3 left
💡 Hint
Common Mistakes
Setting the default header value to a string which makes it always that value.
Using the header name as default value instead of None.
3fill in blank
hard

Fix the error in the code to correctly implement query parameter versioning.

FastAPI
from fastapi import FastAPI, Query, HTTPException
app = FastAPI()

@app.get("/items")
async def read_items(version: str = Query([1])):
    if version != "1":
        raise HTTPException(status_code=400, detail="Unsupported API version")
    return {"items": ["apple", "banana"]}
Drag options to blanks, or click blank then click option'
A"v1"
BNone
C"1"
D"version"
Attempts:
3 left
💡 Hint
Common Mistakes
Setting default to a string makes the parameter always that value.
Using the parameter name as default value.
4fill in blank
hard

Fill both blanks to create two FastAPI routers for version 1 and version 2 with path prefixes.

FastAPI
from fastapi import FastAPI, APIRouter
app = FastAPI()

router_v[1] = APIRouter(prefix="/api/v[1]")
router_v[2] = APIRouter(prefix="/api/v[2]")

@router_v[1].get("/items")
async def get_items_v1():
    return {"version": [1], "items": ["apple"]}

@router_v[2].get("/items")
async def get_items_v2():
    return {"version": [2], "items": ["apple", "banana"]}

app.include_router(router_v[1])
app.include_router(router_v[2])
Drag options to blanks, or click blank then click option'
A1
B2
Cv1
Dv2
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'v1' or 'v2' in the blanks leads to incorrect paths like '/api/vv1/items'.
Mixing version numbers and strings inconsistently.
5fill in blank
hard

Fill all three blanks to implement header versioning with dependency injection in FastAPI.

FastAPI
from fastapi import FastAPI, Header, HTTPException, Depends
app = FastAPI()

def get_api_version([3]: str = Header([1])):
    if [3] not in ["1", "2"]:
        raise HTTPException(status_code=400, detail="Unsupported API version")
    return [3]

@app.get("/items")
async def read_items(version: str = Depends([2])):
    if version == "1":
        return {"items": ["apple"]}
    elif version == "2":
        return {"items": ["apple", "banana"]}
    return {"items": []}
Drag options to blanks, or click blank then click option'
ANone
Bget_api_version
Cx_api_version
D"1"
Attempts:
3 left
💡 Hint
Common Mistakes
Setting header default to a string instead of None.
Not using Depends for dependency injection.
Using wrong parameter names that don't match header.

Practice

(1/5)
1. What is the main purpose of API versioning in FastAPI?
easy
A. To automatically generate API documentation
B. To speed up the API response time
C. To allow multiple versions of an API to coexist and support different clients
D. To encrypt API data for security

Solution

  1. Step 1: Understand API versioning concept

    API versioning lets you keep old and new API versions available so different clients can use the version they need.
  2. Step 2: Identify the main goal

    The main goal is to support multiple API versions simultaneously without breaking existing clients.
  3. Final Answer:

    To allow multiple versions of an API to coexist and support different clients -> Option C
  4. Quick Check:

    API versioning = support multiple versions [OK]
Hint: API versioning means supporting old and new API versions [OK]
Common Mistakes:
  • Thinking versioning speeds up API
  • Confusing versioning with security encryption
  • Assuming versioning auto-generates docs
2. Which of the following is a correct way to define a versioned route in FastAPI using the URL path method?
easy
A. app.get('/items/v1')
B. app.get('/v1/items/')
C. app.get('v1items/')
D. app.get('items/v1')

Solution

  1. Step 1: Check route path syntax

    FastAPI routes must start with a slash '/' to be valid paths.
  2. Step 2: Identify correct version prefix

    Versioning by URL path usually prefixes the version like '/v1/' before the resource path.
  3. Final Answer:

    app.get('/v1/items/') -> Option B
  4. Quick Check:

    Versioned route starts with '/' and version prefix [OK]
Hint: Routes must start with '/' and include version prefix [OK]
Common Mistakes:
  • Omitting leading slash in route path
  • Placing version after resource path incorrectly
  • Using quotes without leading slash
3. Given this FastAPI code snippet, what will be the response when accessing /api/items with header X-API-Version: 2?
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()

@app.get('/api/items')
async def get_items(x_api_version: str | None = Header(None)):
    if x_api_version == '1':
        return {'version': 1, 'items': ['apple', 'banana']}
    elif x_api_version == '2':
        return {'version': 2, 'items': ['orange', 'grape']}
    else:
        raise HTTPException(status_code=400, detail='Unsupported API version')
medium
A. {'version': 1, 'items': ['apple', 'banana']}
B. HTTP 400 Unsupported API version
C. HTTP 404 Not Found
D. {'version': 2, 'items': ['orange', 'grape']}

Solution

  1. Step 1: Check header value handling

    The function reads the header 'X-API-Version' and compares it to '1' or '2'.
  2. Step 2: Match header '2' to response

    Since header is '2', it returns the dictionary with version 2 and items ['orange', 'grape'].
  3. Final Answer:

    {'version': 2, 'items': ['orange', 'grape']} -> Option D
  4. Quick Check:

    Header 'X-API-Version: 2' returns version 2 data [OK]
Hint: Match header value to if-elif branches for output [OK]
Common Mistakes:
  • Ignoring header and returning default
  • Confusing version 1 and 2 outputs
  • Assuming 404 error instead of 400
4. Identify the error in this FastAPI versioning code using query parameters:
from fastapi import FastAPI
app = FastAPI()

@app.get('/items')
async def read_items(version: int = 1):
    if version == 1:
        return {'items': ['pen', 'notebook']}
    elif version == 2:
        return {'items': ['pencil', 'eraser']}
    else:
        return {'error': 'Unsupported version'}
medium
A. The function should raise HTTPException for unsupported versions instead of returning dict
B. The query parameter 'version' should be declared with Query() for validation
C. The route path should include the version like '/v1/items'
D. The default version value should be a string, not int

Solution

  1. Step 1: Check error handling for unsupported versions

    Returning a dict with 'error' key is not standard; better to raise HTTPException with status code.
  2. Step 2: Understand FastAPI error response best practice

    Raising HTTPException sends proper HTTP error status and message to client.
  3. Final Answer:

    The function should raise HTTPException for unsupported versions instead of returning dict -> Option A
  4. Quick Check:

    Use HTTPException for errors, not plain dict [OK]
Hint: Use HTTPException for errors, not just return dict [OK]
Common Mistakes:
  • Returning error dict instead of raising exception
  • Thinking query parameter must use Query() always
  • Assuming version must be in URL path
5. You want to support two API versions in FastAPI: version 1 uses URL path versioning like /v1/users, and version 2 uses header versioning with X-API-Version: 2 on the same /users path. How can you implement this correctly?
hard
A. Create two separate routes: one with path '/v1/users' for version 1, and one with path '/users' that checks header 'X-API-Version' for version 2
B. Use a single route '/users' and check both path and header to decide version
C. Use only header versioning for both versions on '/users' path
D. Use query parameter 'version' for both versions on '/users' path

Solution

  1. Step 1: Separate version 1 and version 2 routes

    Version 1 uses URL path '/v1/users', so define a route with that path.
  2. Step 2: Define version 2 route with header check

    Version 2 uses header on '/users', so define a route '/users' that reads 'X-API-Version' header to confirm version 2.
  3. Final Answer:

    Create two separate routes: one with path '/v1/users' for version 1, and one with path '/users' that checks header 'X-API-Version' for version 2 -> Option A
  4. Quick Check:

    Separate routes for different versioning methods [OK]
Hint: Separate routes for path and header versioning [OK]
Common Mistakes:
  • Mixing path and header versioning in one route
  • Using only header or only path for both versions
  • Trying to detect path version inside header route
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