Skip to content

Add feature to customize the item_id parameter name #174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
14 changes: 14 additions & 0 deletions docs/en/docs/routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@ the [SQLAlchemyCRUDRouter](backends/sqlalchemy.md) will use the model's table na
You are also able to set custom prefixes with the `prefix` kwarg when creating your CRUDRouter. This can be done like so:
`router = CRUDRouter(model=mymodel, prefix='carrot')`

## Custom item_id

If you don't want the default `item_id` as your path parameter name for the item id you can use set the `item_id_parameter_name` key when creating a new CRUDRouter. This will change the parameter name in the OpenAPI specification for you.

```python
SQLAlchemyCRUDRouter(
schema=Potato,
db_model=PotatoModel,
db=session,
prefix="potato",
item_id_parameter_name="potato_id",
)
```

## Disabling Routes
Routes can be disabled from generating with a key word argument (kwarg) when creating your CRUDRouter. The valid kwargs
are shown below.
Expand Down
8 changes: 5 additions & 3 deletions fastapi_crudrouter/core/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def __init__(
update_route: Union[bool, DEPENDENCIES] = True,
delete_one_route: Union[bool, DEPENDENCIES] = True,
delete_all_route: Union[bool, DEPENDENCIES] = True,
item_id_parameter_name: Optional[str] = "item_id",
**kwargs: Any,
) -> None:

Expand All @@ -46,6 +47,7 @@ def __init__(
if update_schema
else schema_factory(self.schema, pk_field_name=self._pk, name="Update")
)
item_id_path = f"/{{{item_id_parameter_name}}}"

prefix = str(prefix if prefix else self.schema.__name__).lower()
prefix = self._base_path + prefix.strip("/")
Expand Down Expand Up @@ -85,7 +87,7 @@ def __init__(

if get_one_route:
self._add_api_route(
"/{item_id}",
item_id_path,
self._get_one(),
methods=["GET"],
response_model=self.schema,
Expand All @@ -96,7 +98,7 @@ def __init__(

if update_route:
self._add_api_route(
"/{item_id}",
item_id_path,
self._update(),
methods=["PUT"],
response_model=self.schema,
Expand All @@ -107,7 +109,7 @@ def __init__(

if delete_one_route:
self._add_api_route(
"/{item_id}",
item_id_path,
self._delete_one(),
methods=["DELETE"],
response_model=self.schema,
Expand Down
2 changes: 2 additions & 0 deletions fastapi_crudrouter/core/databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ def __init__(
update_route: Union[bool, DEPENDENCIES] = True,
delete_one_route: Union[bool, DEPENDENCIES] = True,
delete_all_route: Union[bool, DEPENDENCIES] = True,
item_id_parameter_name: Optional[str] = "item_id",
**kwargs: Any
) -> None:
assert (
Expand All @@ -81,6 +82,7 @@ def __init__(
update_route=update_route,
delete_one_route=delete_one_route,
delete_all_route=delete_all_route,
item_id_parameter_name=item_id_parameter_name,
**kwargs
)

Expand Down
2 changes: 2 additions & 0 deletions fastapi_crudrouter/core/gino_starlette.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def __init__(
update_route: Union[bool, DEPENDENCIES] = True,
delete_one_route: Union[bool, DEPENDENCIES] = True,
delete_all_route: Union[bool, DEPENDENCIES] = True,
item_id_parameter_name: Optional[str] = "item_id",
**kwargs: Any
) -> None:
assert gino_installed, "Gino must be installed to use the GinoCRUDRouter."
Expand All @@ -63,6 +64,7 @@ def __init__(
update_route=update_route,
delete_one_route=delete_one_route,
delete_all_route=delete_all_route,
item_id_parameter_name=item_id_parameter_name,
**kwargs
)

Expand Down
2 changes: 2 additions & 0 deletions fastapi_crudrouter/core/mem.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ def __init__(
update_route: Union[bool, DEPENDENCIES] = True,
delete_one_route: Union[bool, DEPENDENCIES] = True,
delete_all_route: Union[bool, DEPENDENCIES] = True,
item_id_parameter_name: Optional[str] = "item_id",
**kwargs: Any
) -> None:
super().__init__(
Expand All @@ -37,6 +38,7 @@ def __init__(
update_route=update_route,
delete_one_route=delete_one_route,
delete_all_route=delete_all_route,
item_id_parameter_name=item_id_parameter_name,
**kwargs
)

Expand Down
2 changes: 2 additions & 0 deletions fastapi_crudrouter/core/ormar.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def __init__(
update_route: Union[bool, DEPENDENCIES] = True,
delete_one_route: Union[bool, DEPENDENCIES] = True,
delete_all_route: Union[bool, DEPENDENCIES] = True,
item_id_parameter_name: Optional[str] = "item_id",
**kwargs: Any
) -> None:
assert ormar_installed, "Ormar must be installed to use the OrmarCRUDRouter."
Expand All @@ -62,6 +63,7 @@ def __init__(
update_route=update_route,
delete_one_route=delete_one_route,
delete_all_route=delete_all_route,
item_id_parameter_name=item_id_parameter_name,
**kwargs
)

Expand Down
2 changes: 2 additions & 0 deletions fastapi_crudrouter/core/sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def __init__(
update_route: Union[bool, DEPENDENCIES] = True,
delete_one_route: Union[bool, DEPENDENCIES] = True,
delete_all_route: Union[bool, DEPENDENCIES] = True,
item_id_parameter_name: Optional[str] = "item_id",
**kwargs: Any
) -> None:
assert (
Expand All @@ -63,6 +64,7 @@ def __init__(
update_route=update_route,
delete_one_route=delete_one_route,
delete_all_route=delete_all_route,
item_id_parameter_name=item_id_parameter_name,
**kwargs
)

Expand Down
2 changes: 2 additions & 0 deletions fastapi_crudrouter/core/tortoise.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def __init__(
update_route: Union[bool, DEPENDENCIES] = True,
delete_one_route: Union[bool, DEPENDENCIES] = True,
delete_all_route: Union[bool, DEPENDENCIES] = True,
item_id_parameter_name: Optional[str] = "item_id",
**kwargs: Any
) -> None:
assert (
Expand All @@ -54,6 +55,7 @@ def __init__(
update_route=update_route,
delete_one_route=delete_one_route,
delete_all_route=delete_all_route,
item_id_parameter_name=item_id_parameter_name,
**kwargs
)

Expand Down
10 changes: 10 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,13 @@ def string_pk_client(request):
)
def integrity_errors_client(request):
yield from yield_test_client(request.param(), request.param)


@pytest.fixture(
params=[
sqlalchemy_implementation_custom_item_id,
],
scope="function",
)
def custom_item_id_client(request):
yield from yield_test_client(request.param(), request.param)
1 change: 1 addition & 0 deletions tests/implementations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
sqlalchemy_implementation_custom_ids,
sqlalchemy_implementation_integrity_errors,
sqlalchemy_implementation_string_pk,
sqlalchemy_implementation_custom_item_id,
DSN_LIST,
)
from .tortoise_ import tortoise_implementation
Expand Down
40 changes: 40 additions & 0 deletions tests/implementations/sqlalchemy_.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,43 @@ class CarrotModel(Base):
)

return app


def sqlalchemy_implementation_custom_item_id():
app, engine, Base, session = _setup_base_app()

class PotatoModel(Base):
__tablename__ = "potatoes"
id = Column(Integer, primary_key=True, index=True)
thickness = Column(Float)
mass = Column(Float)
color = Column(String, unique=True)
type = Column(String)

class CarrotModel(Base):
__tablename__ = "carrots"
id = Column(Integer, primary_key=True, index=True)
length = Column(Float)
color = Column(String)

Base.metadata.create_all(bind=engine)
app.include_router(
SQLAlchemyCRUDRouter(
schema=Potato,
db_model=PotatoModel,
db=session,
prefix="potato",
item_id_parameter_name="potato_id",
)
)
app.include_router(
SQLAlchemyCRUDRouter(
schema=Carrot,
db_model=CarrotModel,
db=session,
prefix="carrot",
item_id_parameter_name="carrot_id"
)
)

return app
33 changes: 33 additions & 0 deletions tests/test_custom_item_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from . import test_router
from pytest import mark


potato_type = dict(name="russet", origin="Canada")

PATHS = ["/potato", "/carrot"]

class TestOpenAPISpec:
def test_schema_exists(self, custom_item_id_client):
res = custom_item_id_client.get("/openapi.json")
assert res.status_code == 200

return res

@mark.parametrize("path", PATHS)
def test_response_types(self, custom_item_id_client, path):
schema = self.test_schema_exists(custom_item_id_client).json()
paths = schema["paths"]

for method in ["get", "post", "delete"]:
assert "200" in paths[path][method]["responses"]

assert "422" in paths[path]["post"]["responses"]

if path == "/potato":
item_path = path + "/{potato_id}"
else:
item_path = path + "/{carrot_id}"
for method in ["get", "put", "delete"]:
assert "200" in paths[item_path][method]["responses"]
assert "404" in paths[item_path][method]["responses"]
assert "422" in paths[item_path][method]["responses"]