implement http status codes

This commit is contained in:
Marc Koch 2025-03-26 15:21:35 +01:00
parent 878af4465a
commit 8774739861
Signed by: marc.koch
GPG key ID: 12406554CFB028B9

22
main.py
View file

@ -1,5 +1,5 @@
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi import Depends, FastAPI, HTTPException, status, Response
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
import hsadmin
@ -14,8 +14,8 @@ def check_token(token: str) -> bool:
"""Check if the token is valid"""
return token == config.token
@app.put("/list/{listname}")
def create_list(token: Annotated[HTTPAuthorizationCredentials, Depends(security)], listname: str):
@app.put("/list/{listname}", status_code=status.HTTP_201_CREATED)
def create_list(token: Annotated[HTTPAuthorizationCredentials, Depends(security)], listname: str, response: Response):
# Authenticate
if not check_token(token.credentials):
@ -23,15 +23,23 @@ def create_list(token: Annotated[HTTPAuthorizationCredentials, Depends(security)
# Create email
api = hsadmin.login()
# If the email already exists, return an error
if hsadmin.email_exists(api, config.domain, listname):
response.status_code = status.HTTP_409_CONFLICT
return {"Success": "false", "Message": "list already exists"}
# Create the email
result = hsadmin.add_email(api, config.listsuser, config.domain, listname)
if result == True:
return {"Success": "true"}
# If the email could not be created, return an error
response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
return {"Success": "false", "Message": result}
@app.delete("/list/{listname}")
def delete_list(token: Annotated[HTTPAuthorizationCredentials, Depends(security)], listname: str):
@app.delete("/list/{listname}", status_code=status.HTTP_200_OK)
def delete_list(token: Annotated[HTTPAuthorizationCredentials, Depends(security)], listname: str, response: Response):
# Authenticate
if not check_token(token.credentials):
@ -40,8 +48,12 @@ def delete_list(token: Annotated[HTTPAuthorizationCredentials, Depends(security)
# Delete email
api = hsadmin.login()
if not hsadmin.email_exists(api, config.domain, listname):
response.status_code = status.HTTP_404_NOT_FOUND
return {"Success": "false", "Message": "list does not exist"}
result = hsadmin.remove_email(api, config.listsuser, config.domain, listname)
if result == True:
return {"Success": "true"}
# If the email could not be deleted, return an error
response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
return {"Success": "false", "Message": result}