Bird
Raised Fist0
FastAPIframework~10 mins

Health check endpoints 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 create a basic health check endpoint in FastAPI.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
async def health_check():
    return {"status": "[1]"}
Drag options to blanks, or click blank then click option'
Aok
Bhealthy
Crunning
Dup
Attempts:
3 left
💡 Hint
Common Mistakes
Using a status message that is not a string
Forgetting to return a dictionary
Using a wrong HTTP method
2fill in blank
medium

Complete the code to add a health check endpoint that returns HTTP status 200 with JSON response.

FastAPI
from fastapi import FastAPI
from fastapi.responses import Response

app = FastAPI()

@app.get("/health")
async def health_check():
    return Response(content='{"status": "ok"}', media_type="[1]")
Drag options to blanks, or click blank then click option'
Atext/html
Btext/plain
Capplication/xml
Dapplication/json
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text/plain' which is for plain text
Using 'application/xml' which is for XML data
Using 'text/html' which is for HTML pages
3fill in blank
hard

Fix the error in the health check endpoint that should return a JSON response with status code 200.

FastAPI
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/health")
def health_check():
    return [1]({"status": "ok"}, status_code=200)
Drag options to blanks, or click blank then click option'
AResponse
BJSONResponse
CPlainTextResponse
DHTMLResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using Response which requires manual JSON string
Using PlainTextResponse which returns plain text
Using HTMLResponse which returns HTML
4fill in blank
hard

Fill both blanks to create a health check endpoint that returns a JSON with status 'ok' and HTTP status 200.

FastAPI
from fastapi import FastAPI
from fastapi.responses import [1]

app = FastAPI()

@app.get("/health")
async def health_check():
    return [2]({"status": "ok"}, status_code=200)
Drag options to blanks, or click blank then click option'
AJSONResponse
BResponse
CPlainTextResponse
DHTMLResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Response but returning JSONResponse
Using PlainTextResponse which does not return JSON
Mismatching import and return classes
5fill in blank
hard

Fill all three blanks to create a health check endpoint that returns a JSON with a dynamic status message and HTTP status 200.

FastAPI
from fastapi import FastAPI
from fastapi.responses import [1]

app = FastAPI()

@app.get("/health/{status_msg}")
async def health_check(status_msg: str):
    return [2]({"status": [3], status_code=200)
Drag options to blanks, or click blank then click option'
AJSONResponse
BResponse
Cstatus_msg
D"status_msg"
Attempts:
3 left
💡 Hint
Common Mistakes
Putting quotes around status_msg which makes it a string literal
Using Response instead of JSONResponse
Not importing JSONResponse

Practice

(1/5)
1. What is the main purpose of a health check endpoint in a FastAPI application?
easy
A. To serve static files like images
B. To handle user authentication
C. To confirm the app is running and responsive
D. To perform database migrations

Solution

  1. Step 1: Understand the role of health check endpoints

    Health check endpoints are simple URLs that tell if the app is alive and working properly.
  2. Step 2: Identify the correct purpose

    They do not handle authentication, serve files, or migrate databases but confirm app responsiveness.
  3. Final Answer:

    To confirm the app is running and responsive -> Option C
  4. Quick Check:

    Health check = Confirm app alive [OK]
Hint: Health check endpoints confirm app is alive and responsive [OK]
Common Mistakes:
  • Confusing health check with authentication endpoints
  • Thinking health check serves files
  • Assuming health check runs database tasks
2. Which of the following is the correct way to define a simple health check endpoint in FastAPI?
easy
A. @app.get('/health') def health(): return {'status': 'ok'}
B. app.route('/health', method='GET')(def health(): return 'ok')
C. app.get('/health')(def health(): return {'status': 'ok'})
D. def health(): return {'status': 'ok'} app.get('/health', health)

Solution

  1. Step 1: Recall FastAPI syntax for endpoints

    FastAPI uses decorators like @app.get('/path') above the function to define GET endpoints.
  2. Step 2: Check each option's syntax

    @app.get('/health') def health(): return {'status': 'ok'} correctly uses @app.get decorator and defines a function returning JSON. Others have syntax errors or wrong decorator usage.
  3. Final Answer:

    @app.get('/health')\ndef health():\n return {'status': 'ok'} -> Option A
  4. Quick Check:

    Use @app.get decorator for GET endpoints [OK]
Hint: Use @app.get decorator above function for GET endpoints [OK]
Common Mistakes:
  • Using app.get() as a function call instead of decorator
  • Wrong decorator syntax or missing @
  • Returning string instead of JSON/dict
3. Given this FastAPI health check endpoint code, what will be the JSON response when accessed?
@app.get('/health')
def health():
    return {'status': 'healthy', 'uptime': 12345}
medium
A. 500 Internal Server Error
B. {"status": "ok"}
C. 404 Not Found
D. {"status": "healthy", "uptime": 12345}

Solution

  1. Step 1: Analyze the return value of the endpoint

    The function returns a dictionary with keys 'status' and 'uptime' and their values.
  2. Step 2: Understand FastAPI response conversion

    FastAPI converts dict returns to JSON automatically, so the response will be JSON with those keys and values.
  3. Final Answer:

    {"status": "healthy", "uptime": 12345} -> Option D
  4. Quick Check:

    Dict return becomes JSON response [OK]
Hint: Returned dict becomes JSON response automatically [OK]
Common Mistakes:
  • Expecting string instead of JSON
  • Confusing status code with response body
  • Assuming error without code issues
4. What is wrong with this FastAPI health check endpoint code?
from fastapi import FastAPI
app = FastAPI()

@app.get('/health')
def health():
    return status: 'ok'
medium
A. Missing @app.post decorator
B. Syntax error in return statement
C. Function name must be 'health_check'
D. FastAPI app instance not created

Solution

  1. Step 1: Inspect the return statement syntax

    The return line uses 'return status: 'ok'' which is invalid Python syntax; it should be a dictionary like {'status': 'ok'}.
  2. Step 2: Check other parts for correctness

    The decorator @app.get is correct, function name can be anything, and app instance is created properly.
  3. Final Answer:

    Syntax error in return statement -> Option B
  4. Quick Check:

    Return dict with braces, not 'key: value' alone [OK]
Hint: Return a dict with braces, not 'key: value' alone [OK]
Common Mistakes:
  • Writing return without braces for dict
  • Using wrong decorator for GET endpoint
  • Assuming function name is fixed
5. You want to create a health check endpoint in FastAPI that returns HTTP 200 with JSON {'status': 'ok'} if the app is healthy, but HTTP 503 with {'status': 'unhealthy'} if a database connection fails. Which approach correctly implements this?
hard
A. Use try-except inside the endpoint to check DB, return JSON with status code accordingly
B. Always return {'status': 'ok'} and rely on external monitoring for DB status
C. Create two endpoints: one for app status and one for DB status, no status codes
D. Raise an exception if DB fails, FastAPI returns 500 automatically

Solution

  1. Step 1: Understand the requirement for conditional response

    The endpoint must check DB health and respond with different JSON and HTTP status codes based on that.
  2. Step 2: Evaluate options for handling DB check and response

    Use try-except inside the endpoint to check DB, return JSON with status code accordingly uses try-except to check DB and returns JSON with correct status codes, matching the requirement. Others either ignore DB status or do not set proper codes.
  3. Final Answer:

    Use try-except inside the endpoint to check DB, return JSON with status code accordingly -> Option A
  4. Quick Check:

    Use try-except and return JSON with status codes [OK]
Hint: Use try-except and return JSON with proper HTTP status codes [OK]
Common Mistakes:
  • Ignoring database health in the endpoint
  • Not setting HTTP status codes explicitly
  • Relying on default 500 instead of 503 for service unavailable
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