add design first files

main
Fabian Hoppe 2026-02-10 13:37:29 +01:00
parent 4d39052c2e
commit bee27509a4
2 changed files with 332 additions and 0 deletions

View File

@ -0,0 +1,234 @@
from typing import ClassVar, Dict, List, Tuple # noqa: F401
from pydantic import Field, StrictStr
from typing import Any, Optional
from typing_extensions import Annotated
from openapi_server.models.create_customer_request import CreateCustomerRequest
from openapi_server.models.customer import Customer
from openapi_server.models.restaurant import Restaurant
from openapi_server.models.menu_item import MenuItem
from openapi_server.models.order_item import OrderItem
from openapi_server.models.update_customer_request import UpdateCustomerRequest
from openapi_server.models.restaurants_get200_response import RestaurantsGet200Response
from openapi_server.models.restaurants_id_orders_get200_response import RestaurantsIdOrdersGet200Response
from openapi_server.security_api import get_token_BasicAuth
from openapi_server.apis.customers_api_base import BaseCustomersApi
from openapi_server.apis.restaurants_api_base import BaseRestaurantsApi
from openapi_server.apis.orders_api_base import BaseOrdersApi
from fastapi import ( # noqa: F401
HTTPException,
)
customers: List[Customer] = [
Customer(id="1", name="Max Mustermann", email="max.mustermann@hallo-welt.de"),
Customer(id="2", name="Nikolas Neuer", email="niklas.neuer@mail-provider.com")
]
restaurants: List[Restaurant] = [
Restaurant(id="1", name="Peter Chan Chinese Take Away", address="30 Roods, Kirriemuir, Scotland, United Kingdom"),
Restaurant(id="2", name="Pita Pan in Groß-Gerau", address="Mainzer Straße 10, Groß-Gerau, DE 64521"),
Restaurant(id="3", name="Naansense Indian Inspired Eats", address="178 N Franklin St, Chicago, IL 60606"),
Restaurant(id="4", name="Thai Tanic in Plainville", address="1 Man-Mar Dr, Ste 7, Plainville, MA 02762"),
Restaurant(id="5", name="Grill Of Thrones in Þingholt", address="Address Lækjargata, 101 Reykjavík, Iceland"),
Restaurant(id="6", name="Juan in a Million in Austin", address="2300 E Cesar Chavez St, Austin, TX 78702-4604"),
]
menues = {
"1": [
MenuItem(id="1", name="Hähnchen süßsauer", price=14.5),
MenuItem(id="2", name="Teigtaschen", price=7.5),
MenuItem(id="3", name="Pekingente", price=13.5),
MenuItem(id="4", name="Gebratene Nudeln", price=11)
],
"2": [
MenuItem(id="1", name="Maultaschen", price=12),
MenuItem(id="2", name="Zwiebelkuchen", price=12.5),
MenuItem(id="3", name="Rösti", price=11),
],
"3": [
MenuItem(id="1", name="Frühlingsrollen", price=5.5),
MenuItem(id="2", name="Reis", price=8.5),
MenuItem(id="3", name="Curry", price=12)
],
"4": [
MenuItem(id="1", name="Pizza Marinara", price=12),
MenuItem(id="2", name="Pizza Magherita", price=10.5),
MenuItem(id="3", name="Pizza Salami", price=10.5)
],
"5": [
MenuItem(id="1", name="Gegrilltes Hähnchen", price=8.5),
MenuItem(id="2", name="BBQ", price=9.5),
MenuItem(id="3", name="Burger", price=13.5)
],
"6": [
MenuItem(id="1", name="Tacos", price=10),
MenuItem(id="2", name="Chili", price=12.5),
MenuItem(id="3", name="Tortillas", price=15),
]
}
orders = {
"1": [
OrderItem(menuItemId="1", quantity=2),
OrderItem(menuItemId="2", quantity=2)
],
"2": [
OrderItem(menuItemId="1", quantity=1),
OrderItem(menuItemId="2", quantity=1)
],
"3": [
OrderItem(menuItemId="1", quantity=1),
OrderItem(menuItemId="2", quantity=1)
],
"4": [
OrderItem(menuItemId="1", quantity=1),
OrderItem(menuItemId="2", quantity=1)
],
"5": [
OrderItem(menuItemId="1", quantity=1),
OrderItem(menuItemId="2", quantity=1)
],
"6": [
OrderItem(menuItemId="1", quantity=1),
OrderItem(menuItemId="2", quantity=1)
]
}
class MyCustomersApi(BaseCustomersApi):
async def customers_post(
self,
create_customer_request: CreateCustomerRequest,
idempotency_key: Annotated[Optional[StrictStr], Field(description="Unique key to prevent duplicate orders")],
) -> Customer:
if create_customer_request is None:
raise HTTPException(status_code=404, detail="Customer not found")
customer: Customer = Customer(id=idempotency_key, name=create_customer_request.name, email=create_customer_request.email)
customers.append(customer)
raise HTTPException(status_code=201, detail="Customer created")
return customer
async def customers_me_get(
self,
) -> Customer:
"""Returns the authenticated customer's profile"""
return Customer(id="1", name="Max Mustermann", email="max.mustermann@hallo-welt.de")
async def customers_id_get(
self,
id: StrictStr,
) -> Customer:
customer: Customer = next(filter(lambda c: c.id == id, customers), None)
if customer is None:
raise HTTPException(status_code=404, detail="Customer not found")
return customer
async def customers_id_delete(
self,
id: StrictStr,
) -> None:
customer: Customer = next(filter(lambda c: c.id == id, customers), None)
if customer is None:
raise HTTPException(status_code=404, detail="Customer not found")
customers.remove(customer)
raise HTTPException(status_code=204, detail="Customer updated")
return None
async def customers_id_patch(
self,
id: StrictStr,
update_customer_request: UpdateCustomerRequest,
) -> Customer:
if update_customer_request is None:
raise HTTPException(status_code=404, detail="Customer not found")
customer: Customer = next(filter(lambda c: c.id == id, customers), None)
if customer is None:
raise HTTPException(status_code=404, detail="Customer not found")
customers.remove(customer)
customers.append(Customer(id=id, name=update_customer_request.name, email=update_customer_request.email))
raise HTTPException(status_code=201, detail="Customer updated")
return customer
class MyRestaurantsApi(BaseRestaurantsApi):
subclasses: ClassVar[Tuple] = ()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
BaseRestaurantsApi.subclasses = BaseRestaurantsApi.subclasses + (cls,)
async def restaurants_get(
self,
limit: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]],
offset: Optional[Annotated[int, Field(strict=True, ge=0)]],
accept_language: Annotated[Optional[StrictStr], Field(description="Preferred language for localized strings.")],
) -> RestaurantsGet200Response:
response: RestaurantsGet200Response = RestaurantsGet200Response(data=restaurants)
return response
async def restaurants_id_menu_get(
self,
id: StrictStr,
accept_language: Annotated[Optional[StrictStr], Field(description="Preferred language for localized strings.")],
) -> List[MenuItem]:
if id in menues:
return menues[id]
raise HTTPException(status_code=404, detail="Restaurant not found")
async def restaurants_id_orders_get(
self,
id: StrictStr,
limit: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]],
offset: Optional[Annotated[int, Field(strict=True, ge=0)]],
) -> RestaurantsIdOrdersGet200Response:
print(orders[id])
if id in orders:
return RestaurantsIdOrdersGet200Response(data=orders[id])
raise HTTPException(status_code=404, detail="Restaurant not found")
class MyOrdersAPI(BaseOrdersApi):
subclasses: ClassVar[Tuple] = ()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
BaseOrdersApi.subclasses = BaseOrdersApi.subclasses + (cls,)
async def restaurants_id_orders_get(
self,
id: StrictStr,
limit: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]],
offset: Optional[Annotated[int, Field(strict=True, ge=0)]],
) -> RestaurantsIdOrdersGet200Response:
"""Retrieve a paginated list of orders for a specific restaurant."""
if id in orders:
return RestaurantsIdOrdersGet200Response(data=orders[id])
raise HTTPException(status_code=404, detail="Restaurant not found")
async def orders_post(
self,
create_order_request: CreateOrderRequest,
idempotency_key: Annotated[Optional[StrictStr], Field(description="Unique key to prevent duplicate orders")],
) -> Order:
...
async def orders_order_id_get(
self,
orderId: StrictStr,
) -> Order:
...
async def orders_order_id_status_patch(
self,
orderId: StrictStr,
update_order_status_request: UpdateOrderStatusRequest,
) -> Order:
"""Update the status of an existing order."""
...

View File

@ -0,0 +1,98 @@
import openapi_client
from openapi_client.rest import ApiException
from openapi_client.models.create_customer_request import CreateCustomerRequest
from openapi_client.models.update_customer_request import UpdateCustomerRequest
import os
import sys
def cmdline_options():
print("Options:")
print(" --post-customer=[id]")
print(" --get-customer=[id]")
print(" --delete-customer=[id]")
print(" --patch-customer=[id]")
print(" --get-restaurant-menu=[id]")
print(" --get-restaurants")
def api():
configuration = openapi_client.Configuration(
host = "http://localhost:4004"
)
# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.
# Configure HTTP basic authorization: BasicAuth
configuration = openapi_client.Configuration(
username = os.environ["USERNAME"],
password = os.environ["PASSWORD"]
)
if len(sys.argv) <= 1:
cmdline_options()
return
with openapi_client.ApiClient(configuration) as api_client:
api_instance = openapi_client.CustomersApi(api_client)
api_res_instance = openapi_client.RestaurantsApi(api_client)
if "=" in sys.argv[1]:
arg, id = sys.argv[1].split("=")
match arg:
case "--post-customer":
try:
print("Customer name:")
name = input()
print("Customer email:")
email = input()
result = api_instance.customers_post(CreateCustomerRequest(name=name, email=email), id)
print(result)
except ApiException as e:
print("Exception when calling CustomersApi->customers_post: %s\n" % e)
case "--get-customer":
try:
result = api_instance.customers_id_get(id)
print(result)
except ApiException as e:
print("Exception when calling CustomersApi->customers_id_get: %s\n" % e)
case "--delete-customer":
try:
result = api_instance.customers_id_delete(id)
print(result)
except ApiException as e:
print("Exception when calling CustomersApi->customers_id_delete: %s\n" % e)
case "--patch-customer":
try:
print("Customer name:")
name = input()
print("Customer email:")
email = input()
result = api_instance.customers_id_patch(id, UpdateCustomerRequest(name=name, email=email))
print(result)
except ApiException as e:
print("Exception when calling CustomersApi->customers_id_patch: %s\n" % e)
case "--get-restaurant-menu":
try:
result = api_res_instance.restaurants_id_menu_get(id)
print(result)
except ApiException as e:
print("Exception when calling RestaurantsApi->restaurants_id_menu_get: %s\n" % e)
case _:
cmdline_options()
else:
arg = sys.argv[1]
match arg:
case "--get-restaurants":
try:
result = api_res_instance.restaurants_get()
print(result)
except ApiException as e:
print("Exception when calling RestaurantsApi->restaurants_get: %s\n" % e)
case _:
cmdline_options()
if __name__ == "__main__":
api()