Skip to content
Merged
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ The API provides the following endpoints:
|---|---|---|
| GET | `/health` | `Checks if the API is running.` |
| GET | `/restaurants` | `Lists all the restaurants.` |
| GET | `/restaurants?{query}` | `Lists all the restaurants that match searching query: name=...&hasMenu=...&sort_by=...&sort_desc=...` |
| GET | `/restaurants/{restaurant_id}` | `Retrieves a specific restaurant by its ID.` |


## API Documentation

Expand Down
32 changes: 26 additions & 6 deletions backend/app/api/routes.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from fastapi import FastAPI, HTTPException
from fastapi import FastAPI, HTTPException, Depends
from json import JSONDecodeError

from backend.app.core.dependencies import get_restaurant_service
from backend.app.schemas.restaurant import Restaurant
from backend.app.schemas.restaurant_query import RestaurantQuery
from backend.app.services.restaurant_service import RestaurantService

def create_routes(app: FastAPI):
Expand All @@ -11,14 +12,33 @@ async def health():
return {"status": "ok"}

@app.get("/restaurants", response_model=list[Restaurant])
def list_restaurants():
def list_restaurants(params: RestaurantQuery = Depends()):
restaurant_service = get_restaurant_service()

try:
return restaurant_service.list_restaurants()
return restaurant_service.list_restaurants(
name=params.name,
has_menu=params.hasMenu,
sort_by=params.sort_by,
sort_desc=params.sort_desc
)

except JSONDecodeError:
raise HTTPException(status_code=500, detail="Restaurant data failed to due to invalid JSON")

except ValueError:
except ValueError as e:
if "Invalid sort_by" in str(e):
raise HTTPException(status_code=400, detail=str(e))
raise HTTPException(status_code=500, detail="Restaurant data failed to follow correct list[Restaurant] schema")


@app.get("/restaurants/{restaurant_id}", response_model=Restaurant)
def get_restaurant(restaurant_id: str):
restaurant_service = get_restaurant_service()

try:
restaurant = restaurant_service.get_restaurant_by_id(restaurant_id)
if not restaurant:
raise HTTPException(status_code=404, detail="Restaurant not found")
return restaurant
except JSONDecodeError:
raise HTTPException(status_code=500, detail="Invalid JSON data")
10 changes: 9 additions & 1 deletion backend/app/repositories/restaurant_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,12 @@ def __load_restaurants(self) -> list[Restaurant]:
raise ValueError(f"{self.restaurants_file_path.absolute()} does not follow the correct list[Restaurant] schema. See backend/app/schemas/restaurant.py or visit https://www.schema.org/Restaurant for schema specifications.") from e

def get_all_restaurants(self) -> list[Restaurant]:
return self.__load_restaurants()
return self.__load_restaurants()

def get_restaurant_by_id(self, restaurant_id: str) -> Restaurant | None:
restaurants = self.get_all_restaurants()

for restaurant in restaurants:
if restaurant.id == restaurant_id:
return restaurant
return None
2 changes: 1 addition & 1 deletion backend/app/schemas/restaurant.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ class Restaurant(BaseModel):
address: str
telephone: str
openingHours: str
hasMenu: Menu
hasMenu: Menu | None = None
15 changes: 15 additions & 0 deletions backend/app/schemas/restaurant_query.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from typing import Optional
from fastapi import Query, Depends

class RestaurantQuery:
def __init__(
self,
name: Optional[str] = Query(default=None, description="Filter by restaurant name"),
hasMenu: Optional[bool] = Query(default=None, description="Filter by menu availability"),
sort_by: Optional[str] = Query(default=None, description="Field to sort by (e.g., 'name')"),
sort_desc: bool = Query(default=False, description="Sort in descending order")
):
self.name = name
self.hasMenu = hasMenu
self.sort_by = sort_by
self.sort_desc = sort_desc
30 changes: 28 additions & 2 deletions backend/app/services/restaurant_service.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
from backend.app.repositories.restaurant_repository import RestaurantRepository
from backend.app.schemas.restaurant import Restaurant


class RestaurantService:
def __init__(self, repository: RestaurantRepository):
self.repository: RestaurantRepository = repository

def list_restaurants(self):
return self.repository.get_all_restaurants()
def list_restaurants(self, name=None, has_menu=None, sort_by=None, sort_desc=False):
restaurantsList = self.repository.get_all_restaurants()

if name:
restaurantsList = [r for r in restaurantsList if name.lower() in r.name.lower()]
if has_menu is not None:
restaurantsList = [r for r in restaurantsList if (r.hasMenu is not None) == has_menu]

if sort_by:
if sort_by not in Restaurant.model_fields:
allowed_fields = ", ".join(Restaurant.model_fields.keys())
raise ValueError(f"Invalid sort_by field: '{sort_by}'. Allowed fields: {allowed_fields}")

def get_sort_value(r):
val = getattr(r, sort_by)

if sort_by == "hasMenu":
return val is None

return val if val is not None else ""

restaurantsList.sort(key=get_sort_value, reverse=sort_desc)

return restaurantsList

def get_restaurant_by_id(self, restaurant_id: str):
return self.repository.get_restaurant_by_id(restaurant_id)
44 changes: 44 additions & 0 deletions backend/tests/test_restaurant_id_endpoint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import warnings
from pydantic import TypeAdapter
from backend.app.schemas.restaurant import Restaurant

def get_valid_restaurant_id(client):
"""Helper function to grab a real ID from the database for testing."""
response = client.get("/restaurants")
data = response.json()
if response.status_code == 200 and len(data) > 0:
return data[0]["id"]
return None

def test_restaurant_id_endpoint_returns_200(client):
test_id = get_valid_restaurant_id(client)

if not test_id:
warnings.warn("This couldn't be tested correctly because there were no restaurants.")
return

response = client.get(f"/restaurants/{test_id}")
assert response.status_code == 200, f"Failed! Server returned: {response.json()}"

def test_restaurant_id_endpoint_returns_valid_json(client):
test_id = get_valid_restaurant_id(client)

if not test_id:
warnings.warn("This couldn't be tested correctly because there were no restaurants.")
return

response = client.get(f"/restaurants/{test_id}")
assert response.status_code == 200, f"Failed! Server returned: {response.json()}"
data = response.json()

adapter = TypeAdapter(Restaurant)
restaurant = adapter.validate_python(data)

assert restaurant.id == test_id

def test_restaurant_id_endpoint_returns_404_for_invalid_id(client):
response = client.get("/restaurants/this-id-does-not-exist-999")

assert response.status_code == 404, f"Expected 404, but got: {response.status_code}"
data = response.json()
assert "detail" in data
43 changes: 43 additions & 0 deletions backend/tests/test_restaurant_id_repository.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import pytest
import json
from backend.app.repositories.restaurant_repository import RestaurantRepository

DUMMY_JSON = [
{
"type": "Restaurant",
"id": "123",
"name": "Burger Joint",
"address": "123 Main St",
"telephone": "555-0100",
"openingHours": "Mo-Su 09:00-22:00",
"hasMenu": None
},
{
"type": "Restaurant",
"id": "456",
"name": "Pizza Place",
"address": "456 Oak St",
"telephone": "555-0200",
"openingHours": "Mo-Su 11:00-23:00",
"hasMenu": None
}
]

@pytest.fixture
def test_repo(tmp_path):
"""Creates a temporary JSON file and initializes the repository with it."""
file_path = tmp_path / "test_restaurants.json"
file_path.write_text(json.dumps(DUMMY_JSON))
return RestaurantRepository(restaurants_file_path=file_path)

def test_get_restaurant_by_id_success(test_repo):
restaurant = test_repo.get_restaurant_by_id("456")

assert restaurant is not None
assert restaurant.id == "456"
assert restaurant.name == "Pizza Place"

def test_get_restaurant_by_id_not_found(test_repo):
restaurant = test_repo.get_restaurant_by_id("non-existent-id")

assert restaurant is None
32 changes: 31 additions & 1 deletion backend/tests/test_restaurants_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,34 @@ def test_restaurants_endpoint_returns_valid_json(client):
restaurants = adapter.validate_python(data)

if len(restaurants) == 0:
warnings.warn("This couldn't be tested correctly because there were no restaurants.")
warnings.warn("This couldn't be tested correctly because there were no restaurants.")

def test_restaurants_endpoint_with_name_query(client):
response = client.get("/restaurants?name=Starbucks")
assert response.status_code == 200, f"Failed! Server returned: {response.json()}"
data = response.json()

adapter = TypeAdapter(list[Restaurant])

restaurants = adapter.validate_python(data)

if len(restaurants) == 0:
warnings.warn("This couldn't be tested correctly because there were no restaurants.")

def test_restaurants_endpoint_with_has_menu_query(client):
response = client.get("/restaurants?hasMenu=true")
assert response.status_code == 200, f"Failed! Server returned: {response.json()}"
data = response.json()

adapter = TypeAdapter(list[Restaurant])

restaurants = adapter.validate_python(data)

if len(restaurants) == 0:
warnings.warn("This couldn't be tested correctly because there were no restaurants.")

def test_restaurants_endpoint_with_invalid_sort_by_query(client):
response = client.get("/restaurants?sort_by=non_existent_field")

assert response.status_code == 400
assert "Invalid sort_by" in response.json()["detail"]
88 changes: 88 additions & 0 deletions backend/tests/test_restaurants_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import pytest
from unittest.mock import Mock

from backend.app.schemas.restaurant import Restaurant
from backend.app.schemas.menu import Menu
from backend.app.services.restaurant_service import RestaurantService
@pytest.fixture
def dummy_restaurants():
menu = Menu.model_construct()

return [
Restaurant(id="1", name="Alpha Bites", address="123 Main St", telephone="111", openingHours="9-5", hasMenu=menu, type="restaurant"),
Restaurant(id="2", name="Zeta Grill", address="456 Oak St", telephone="222", openingHours="10-10", hasMenu=None, type="restaurant"),
Restaurant(id="3", name="Beta Bakery", address="789 Pine St", telephone="333", openingHours="6-2", hasMenu=menu, type="restaurant"),
Restaurant(id="4", name="Alpha Cafe", address="321 Elm St", telephone="444", openingHours="8-4", hasMenu=None, type="restaurant"),
]
@pytest.fixture
def mock_repository(dummy_restaurants):
repo = Mock()
repo.get_all_restaurants.return_value = dummy_restaurants
return repo

@pytest.fixture
def restaurant_service(mock_repository):
return RestaurantService(repository=mock_repository)


class TestRestaurantService:

def test_list_restaurants_no_filters(self, restaurant_service, dummy_restaurants):

results = restaurant_service.list_restaurants()

assert len(results) == 4
assert results == dummy_restaurants
restaurant_service.repository.get_all_restaurants.assert_called_once()

def test_filter_by_name_exact_match(self, restaurant_service):
results = restaurant_service.list_restaurants(name="Zeta Grill")
assert len(results) == 1
assert results[0].name == "Zeta Grill"

def test_filter_by_name_partial_case_insensitive(self, restaurant_service):
results = restaurant_service.list_restaurants(name="aLpHa")
assert len(results) == 2
names = [r.name for r in results]
assert "Alpha Bites" in names
assert "Alpha Cafe" in names

def test_filter_by_has_menu_true(self, restaurant_service):
results = restaurant_service.list_restaurants(has_menu=True)
assert len(results) == 2
for r in results:
assert r.hasMenu is not None

def test_filter_by_has_menu_false(self, restaurant_service):
results = restaurant_service.list_restaurants(has_menu=False)
assert len(results) == 2
for r in results:
assert r.hasMenu is None

def test_sort_by_name_ascending(self, restaurant_service):
results = restaurant_service.list_restaurants(sort_by="name", sort_desc=False)
assert len(results) == 4
assert results[0].name == "Alpha Bites"
assert results[1].name == "Alpha Cafe"
assert results[2].name == "Beta Bakery"
assert results[3].name == "Zeta Grill"

def test_sort_by_name_descending(self, restaurant_service):
results = restaurant_service.list_restaurants(sort_by="name", sort_desc=True)
assert len(results) == 4
assert results[0].name == "Zeta Grill"
assert results[1].name == "Beta Bakery"
assert results[2].name == "Alpha Cafe"
assert results[3].name == "Alpha Bites"

def test_sort_by_invalid_attribute(self, restaurant_service, dummy_restaurants):
with pytest.raises(ValueError) as exc_info:
restaurant_service.list_restaurants(sort_by="non_existent_field")
assert "Invalid sort_by" in str(exc_info.value)

def test_combine_filter_and_sort(self, restaurant_service):
results = restaurant_service.list_restaurants(name="Alpha", sort_by="name", sort_desc=True)

assert len(results) == 2
assert results[0].name == "Alpha Cafe"
assert results[1].name == "Alpha Bites"
Loading