|
| 1 | +--- |
| 2 | +description: Rules for FastAPI route definitions and HTTP handling |
| 3 | +globs: ["app.py"] |
| 4 | +alwaysApply: true |
| 5 | +--- |
| 6 | + |
| 7 | +# FastAPI Routes Guidelines |
| 8 | + |
| 9 | +Routes handle HTTP request/response logic. Keep routes thin - validate input, call utility functions, format responses. |
| 10 | + |
| 11 | +## Route Structure |
| 12 | + |
| 13 | +Routes are defined directly in `app.py`: |
| 14 | + |
| 15 | +```python |
| 16 | +from fastapi import FastAPI, responses, status |
| 17 | +from fastapi.encoders import jsonable_encoder |
| 18 | +from submodules.model.business_objects import general |
| 19 | +import util |
| 20 | + |
| 21 | +app = FastAPI(title="refinery-updater") |
| 22 | + |
| 23 | +@app.post("/update_to_newest") |
| 24 | +def update_to_newest() -> responses.PlainTextResponse: |
| 25 | + session_token = general.get_ctx_token() |
| 26 | + if util.update_to_newest(): |
| 27 | + msg = "updated to current version" |
| 28 | + else: |
| 29 | + msg = "nothing to update" |
| 30 | + general.remove_and_refresh_session(session_token) |
| 31 | + return responses.PlainTextResponse(status_code=status.HTTP_200_OK, content=msg) |
| 32 | +``` |
| 33 | + |
| 34 | +## Response Patterns |
| 35 | + |
| 36 | +**Plain text responses:** |
| 37 | +```python |
| 38 | +@app.post("/update_to_newest") |
| 39 | +def update_to_newest() -> responses.PlainTextResponse: |
| 40 | + # ... logic ... |
| 41 | + return responses.PlainTextResponse( |
| 42 | + status_code=status.HTTP_200_OK, |
| 43 | + content="updated to current version" |
| 44 | + ) |
| 45 | +``` |
| 46 | + |
| 47 | +**JSON responses:** |
| 48 | +```python |
| 49 | +@app.get("/version_overview") |
| 50 | +def version_overview() -> responses.JSONResponse: |
| 51 | + session_token = general.get_ctx_token() |
| 52 | + return_values = util.version_overview() |
| 53 | + general.remove_and_refresh_session(session_token) |
| 54 | + return responses.JSONResponse( |
| 55 | + status_code=status.HTTP_200_OK, |
| 56 | + content=jsonable_encoder(return_values), |
| 57 | + ) |
| 58 | +``` |
| 59 | + |
| 60 | +**Conditional response types:** |
| 61 | +```python |
| 62 | +@app.get("/has_updates") |
| 63 | +def has_updates(as_html_response: bool = False) -> responses.JSONResponse: |
| 64 | + session_token = general.get_ctx_token() |
| 65 | + return_value = util.has_updates() |
| 66 | + general.remove_and_refresh_session(session_token) |
| 67 | + if as_html_response: |
| 68 | + return responses.HTMLResponse(content=str(return_value)) |
| 69 | + return responses.JSONResponse( |
| 70 | + status_code=status.HTTP_200_OK, |
| 71 | + content=return_value, |
| 72 | + ) |
| 73 | +``` |
| 74 | + |
| 75 | +## Session Management |
| 76 | + |
| 77 | +**Always manage database sessions:** |
| 78 | +```python |
| 79 | +@app.post("/endpoint") |
| 80 | +def endpoint(): |
| 81 | + session_token = general.get_ctx_token() |
| 82 | + try: |
| 83 | + # ... database operations ... |
| 84 | + return responses.JSONResponse(...) |
| 85 | + finally: |
| 86 | + general.remove_and_refresh_session(session_token) |
| 87 | +``` |
| 88 | + |
| 89 | +## Request Body Models |
| 90 | + |
| 91 | +Use Pydantic models for request validation: |
| 92 | + |
| 93 | +```python |
| 94 | +from pydantic import BaseModel |
| 95 | + |
| 96 | +class UpgradeToAWS(BaseModel): |
| 97 | + only_existing: bool |
| 98 | + remove_from_minio: bool |
| 99 | + force_overwrite: bool |
| 100 | + |
| 101 | +@app.post("/migrate_minio_to_aws") |
| 102 | +def migrate_minio_to_aws(request: UpgradeToAWS) -> int: |
| 103 | + from upgrade_logic.pre_redesign.upgrade_from_minio_to_aws import upgrade |
| 104 | + upgrade(request.only_existing, request.remove_from_minio, request.force_overwrite) |
| 105 | + return 0 |
| 106 | +``` |
| 107 | + |
| 108 | +## Query Parameters |
| 109 | + |
| 110 | +```python |
| 111 | +@app.get("/has_updates") |
| 112 | +def has_updates(as_html_response: bool = False) -> responses.JSONResponse: |
| 113 | + # Query parameter with default value |
| 114 | + pass |
| 115 | +``` |
| 116 | + |
| 117 | +## Health Check Pattern |
| 118 | + |
| 119 | +```python |
| 120 | +@app.get("/healthcheck") |
| 121 | +def healthcheck() -> responses.PlainTextResponse: |
| 122 | + text = "" |
| 123 | + status_code = status.HTTP_200_OK |
| 124 | + database_test = general.test_database_connection() |
| 125 | + if not database_test.get("success"): |
| 126 | + error_name = database_test.get("error") |
| 127 | + text += f"database_error:{error_name}:" |
| 128 | + status_code = status.HTTP_500_INTERNAL_SERVER_ERROR |
| 129 | + if not text: |
| 130 | + text = "OK" |
| 131 | + return responses.PlainTextResponse(text, status_code=status_code) |
| 132 | +``` |
| 133 | + |
| 134 | +## Error Handling |
| 135 | + |
| 136 | +Handle errors gracefully and return appropriate status codes: |
| 137 | + |
| 138 | +```python |
| 139 | +@app.post("/endpoint") |
| 140 | +def endpoint(): |
| 141 | + session_token = general.get_ctx_token() |
| 142 | + try: |
| 143 | + result = util.some_operation() |
| 144 | + return responses.JSONResponse( |
| 145 | + status_code=status.HTTP_200_OK, |
| 146 | + content=jsonable_encoder(result), |
| 147 | + ) |
| 148 | + except Exception as e: |
| 149 | + print(f"Error: {e}", flush=True) |
| 150 | + return responses.PlainTextResponse( |
| 151 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 152 | + content=f"Error: {str(e)}", |
| 153 | + ) |
| 154 | + finally: |
| 155 | + general.remove_and_refresh_session(session_token) |
| 156 | +``` |
| 157 | + |
| 158 | +## Best Practices |
| 159 | + |
| 160 | +1. **Keep routes thin**: Delegate business logic to `util.py` or `upgrade_logic/` |
| 161 | +2. **Session management**: Always use `get_ctx_token()` and `remove_and_refresh_session()` |
| 162 | +3. **Type hints**: Use return type annotations (`-> responses.PlainTextResponse`) |
| 163 | +4. **Status codes**: Use appropriate HTTP status codes from `status` module |
| 164 | +5. **JSON encoding**: Use `jsonable_encoder()` for complex objects |
| 165 | +6. **Error handling**: Handle exceptions and return appropriate error responses |
| 166 | +7. **Route naming**: Use snake_case for route paths: `/update_to_newest`, `/version_overview` |
| 167 | +8. **Health checks**: Include health check endpoints that test critical dependencies |
0 commit comments