Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 16 additions & 14 deletions folksonomy/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from . import db
from . import settings
from fastapi.middleware.cors import CORSMiddleware

from typing import List, Optional, Dict, Any, Union

description = """
Folksonomy Engine API allows you to add free property/value pairs to Open Food Facts products.
Expand Down Expand Up @@ -75,7 +75,7 @@ async def initialize_transactions(request: Request, call_next):
return response


@app.get("/", status_code=status.HTTP_200_OK)
@app.get("/", status_code=status.HTTP_200_OK, response_model=HelloResponse)
async def hello():
return {"message": "Hello folksonomy World! Tip: open /docs for documentation"}

Expand Down Expand Up @@ -146,7 +146,7 @@ def get_auth_server(request: Request):
return base_url


@app.post("/auth")
@app.post("/auth", response_model=TokenResponse)
async def authentication(request: Request, response: Response, form_data: OAuth2PasswordRequestForm = Depends()):
"""
Authentication: provide user/password and get a bearer token in return
Expand Down Expand Up @@ -195,7 +195,7 @@ async def authentication(request: Request, response: Response, form_data: OAuth2
status_code=500, detail="Server error")


@app.post("/auth_by_cookie")
@app.post("/auth_by_cookie", response_model=TokenResponse)
async def authentication(request: Request, response: Response, session: Optional[str] = Cookie(None)):
"""
Authentication: provide Open Food Facts session cookie and get a bearer token in return
Expand Down Expand Up @@ -410,7 +410,7 @@ async def product_tag_list_versions(response: Response,
return JSONResponse(status_code=200, content=out[0], headers={"x-pg-timing": timing})


@app.post("/product")
@app.post("/product", response_model=Dict[str, str])
async def product_tag_add(response: Response,
product_tag: ProductTag,
user: User = Depends(get_current_user)):
Expand Down Expand Up @@ -439,11 +439,11 @@ async def product_tag_add(response: Response,
return JSONResponse(status_code=422, content={"detail": {"msg": error_msg}})

if cur.rowcount == 1:
return "ok"
return {"status": "ok"}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're changing the API here. @CharlesNepote is that ok?

Copy link
Contributor Author

@suchithh suchithh Mar 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're changing the API here. @CharlesNepote is that ok?

Regarding the change in the response model from a string ("ok") to a dict ({"status": "ok"}): while this change might affect the API, upgrading all responses to Pydantic models is key in the long run. One of FastAPI's core conventions is to use Pydantic models as much as possible, and changing the response structure now could potentially save many headaches in the future. Additionally, for validation failures (422), the response is already a JSON structure; depending on how the endpoint is used, it might be harder to check types on the frontend than to maintain consistency. Just my two cents.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@suchithh I understand your concern, but API change might have impact on reusers: we need to talk with them first and evaluate potential impacts.
So you should push a first PR without modifying the API, and a second one to push API changes.

return


@app.put("/product")
@app.put("/product", response_model=Dict[str, str])
async def product_tag_update(response: Response,
product_tag: ProductTag,
user: User = Depends(get_current_user)):
Expand All @@ -469,7 +469,7 @@ async def product_tag_update(response: Response,
detail=re.sub(r'.*@@ (.*) @@\n.*$', r'\1', e.pgerror)[:-1],
)
if cur.rowcount == 1:
return "ok"
return {"status": "ok"}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment.

elif cur.rowcount == 0: # non existing key
raise HTTPException(
status_code=404,
Expand All @@ -478,11 +478,11 @@ async def product_tag_update(response: Response,
else:
raise HTTPException(
status_code=503,
detail="Doubious update - more than one row udpated",
detail="Dubious update - more than one row udpated",
)


@app.delete("/product/{product}/{k}")
@app.delete("/product/{product}/{k}", response_model=Dict[str, str])
async def product_tag_delete(response: Response,
product: str, k: str, version: int, owner='',
user: User = Depends(get_current_user)):
Expand All @@ -507,6 +507,8 @@ async def product_tag_delete(response: Response,
status_code=422,
detail=re.sub(r'.*@@ (.*) @@\n.*$', r'\1', e.pgerror)[:-1],
)
if cur.rowcount == 1:
return {"status": "ok"}
if cur.rowcount != 1:
raise HTTPException(
status_code=422,
Expand All @@ -519,7 +521,7 @@ async def product_tag_delete(response: Response,
(product, owner, k.lower()),
)
if cur.rowcount == 1:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This and the next line are redundant with line 510-511.

return "ok"
return {"status": "ok"}
else:
# we have a conflict, return an error explaining conflict
cur, timing = await db.db_exec(
Expand Down Expand Up @@ -570,7 +572,7 @@ async def keys_list(response: Response,
return JSONResponse(status_code=200, content=out[0], headers={"x-pg-timing": timing})


@app.get("/values/{k}")
@app.get("/values/{k}", response_model=List[ValueCount])
async def get_unique_values(response: Response,
k: str,
owner: str = '',
Expand Down Expand Up @@ -622,11 +624,11 @@ async def get_unique_values(response: Response,
return JSONResponse(status_code=200, content=data, headers={"x-pg-timing": timing})


@app.get("/ping")
@app.get("/ping", response_model=PingResponse)
async def pong(response: Response):
"""
Check server health
"""
cur, timing = await db.db_exec("SELECT current_timestamp AT TIME ZONE 'GMT'",())
pong = await cur.fetchone()
return {"ping": "pong @ %s" % pong[0]}
return {"ping": "pong @ %s" % pong[0]}
12 changes: 10 additions & 2 deletions folksonomy/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,13 @@
from pydantic import BaseModel, ValidationError, validator

# folksonomy imports
from .models import ProductTag, ProductStats, User, ProductList

from .models import (
ProductTag,
ProductStats,
User,
ProductList,
HelloResponse,
TokenResponse,
PingResponse,
ValueCount,
)
18 changes: 18 additions & 0 deletions folksonomy/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,21 @@ class ProductList(BaseModel):
product: str
k: str
v: str


class HelloResponse(BaseModel):
message: str


class TokenResponse(BaseModel):
access_token: str
token_type: str


class PingResponse(BaseModel):
ping: str


class ValueCount(BaseModel):
v: str
product_count: int
Loading