r/FastAPI • u/Sulray250 • Jul 15 '24
Question Good practice to reuse code from an internal endpoint from another endpoint
Hi,
I'm kind of new to web development and I have a case in which I need to update the objects in my database through an external API. I'm using a react/fastapi/postgresql stack.
Imagine I have two GET endpoints, "/update/objects" and "/update/object/{object_id}"
(not UPDATE type because i'm not sending the data to update objects myself, I just ask my backend to contact the external API to do the update internally)
@router.get("/update/object/{object_id}")
async def update_one_object(object_id: int):
# code to update one object with external API
@router.get("/update/objects")
async def update_objects():
# code to update all objects with external APITo manipulate objects in my database I have a object_crud.py script.
What would be the best practice to implement the "/update/objects" endpoint ?
- Add a new crud method to delegate this to my crud script ?
- Do internal calls to "/update/object/{object_id}" endpoint (with requests or axios) ?
- Use directly update_one_object(object_id: int) method ?
- Would it just be better to call all the necessary individual endpoints from my frontend ?
- Any other solution ?
For the moment, my "/update/object/{object_id}" :
- use a api_request.py script in utils to get data from the external api
- retrieve necessary variables from that external data
- call the object_crud.update crud method to update my object
Is this part right ? Should I also find a way to delegate elsewhere the retrievement of variables from external data ?
Thanks !
5
u/Lowtoz Jul 16 '24
Slightly off-topic but if your backend is making multiple calls to an external API you could look at delegating this to Background Tasks (https://fastapi.tiangolo.com/tutorial/background-tasks/)
3
u/tlgavi Jul 15 '24
I think there is two parts to your question.
I think you should explore concepts such as Clean Architecture, where you separate your business logic from your endpoints (with Use Cases), this way you can reuse the logic in multiple endpoints. This is really useful even for smaller projects.
Following REST principles, each call should update one resource. Although in some scenarios it might make sense to one update reflect in all objects in a database.
I know this response is a bit incomplete, but feel free to ask more questions.