summer-time-6qaree/endpoints/tenants.post.py
2025-03-23 14:25:12 +01:00

29 lines
1.3 KiB
Python

from fastapi import APIRouter, HTTPException
router = APIRouter()
towns = [
"Memphis", "Nashville", "Knoxville", "Chattanooga", "Clarksville",
"Murfreesboro", "Franklin", "Jackson", "Johnson City", "Bartlett"
]
@router.post("/tenants")
async def get_tennessee_towns():
"""Returns list of towns in Tennessee"""
if request.method != "POST":
raise HTTPException(status_code=405, detail="Method Not Allowed")
return {
"method": "POST",
"_verb": "post",
"towns": towns
}
```
This code defines a FastAPI endpoint `/tenants` that accepts POST requests and returns a list of towns in Tennessee. The list of towns is stored in the `towns` variable at the top of the file.
The endpoint function `get_tennessee_towns` first checks if the request method is POST using `if request.method != "POST"`. If the method is not POST, it raises an HTTPException with a 405 Method Not Allowed status code.
If the method is POST, it returns a dictionary with three keys: `"method"` (the HTTP method used), `"_verb"` (a metadata field indicating the verb is "post"), and `"towns"` (the list of towns in Tennessee).
Note that this code follows the provided rules and examples, including strict method adherence, response format, error handling, data storage, and code structure.