HackSoftware / Django-Styleguide

Django styleguide used in HackSoft projects
MIT License
5k stars 511 forks source link

Third party APIs #153

Open elias-ebrahimpour opened 3 months ago

elias-ebrahimpour commented 3 months ago

Hello and greetings,

I have a question for which I did not find a suitable answer. In most of my projects, we had some third-party services or APIs to call (with requests or http.client). Where do I have to put them? In the services file/folder or selectors, or anywhere else?

Finally, thanks for this good style guide.

RadoRado commented 3 months ago

@elias-ebrahimpour Hello :wave:

Perhaps, the best way to illustrate our approach is within our Styleguide Example - https://github.com/HackSoftware/Django-Styleguide-Example/blob/master/styleguide_example/integrations/aws/client.py

We tend to write "clients" for everything that goes outside the system, and then, interact with those clients in the service layer and/or task layer, whenever is necessary.

Yet, the most important thing for those clients is to define an interface for interaction with something outside of our current & existing system.

Let me know if this answers your questions and you need me to put few more sentences together.

Cheers!

elias-ebrahimpour commented 3 months ago

@RadoRado Thank you for your response and time. I've gotten my answer but if you want to explain more about this issue, I'm all ears.

Cheers!

devmitrandir commented 2 months ago

@RadoRado Hi!

For example, I have 2 applications: integrations and blog.

I need to fetch data from a third party API once a day and save. My models are in the blog application.

In which application is it better to add logic?

I think I need to add the client in integrations and use it in blog/services.py. And call this service from a celery task (blog/tasks.py).

RadoRado commented 2 months ago

@devmitrandir This is how I think about it:

  1. Whatever happens for the blog app should be position in the blog app.
  2. Now, if the communication with an external service requires some form of "ritual", you can create a client in the respective integrations app.
  3. And just use this client / sdk in the code inside your blog app.

That's basically all there is.

The general idea for the integrations app is to separate the code for communication with external services and expose a better-suited interface / API for the application.

Now, I'd argue if you only need to make one requests call - you don't need that.

But usually, there are credentials & error handling in play and it's good to live outside your domain.

Again, this is a good example for me - https://github.com/HackSoftware/Django-Styleguide-Example/blob/master/styleguide_example/integrations/aws/client.py

@elias-ebrahimpour this may also be helpful for you too.

devmitrandir commented 2 months ago

@RadoRado Thank you very much!