Reputation: 936
I have an Angular app that consume API client side. Since it's bad practice to do so (I don't want to expose my API credentials), I decided to split into backend/ frontend before myapp get to big. I succeed to implement my Angular into a Django REST framework app and everything is working fine. But now I need to change my API logic and have DRF consume the external API
I had:
Angular <---API---> ext data
Now I have:
Django/ Angular <---API---> ext data
What I need:
Angular <---API---> Django <---API---> ext data
But I am very confused about how to accomplish it. I have experience with setting up API endpoints in DRF, but only for data from models within DRF. I know as well how to consume API in Django. But how can I chain two API calls? Do I have to create a model to store the queries and then the response? Do I need to write serializers even if the returned data is json all the way? How my frontend will now that the data from the external API is available?
What I need is someone to explain me what is the pattern for this task.
Upvotes: 1
Views: 1201
Reputation: 844
Say you have a FBV mapped to an URL in django like this:
url: /api/animals/<str:key>
@add_decorators_as_needed
def animals_view(request, key=None):
data = requests.get(f'{API_URL}/{key}?api_key={API_KEY}') # grab data from ext provider
json_data = ... # convert to json or do other manipulations
return json_data # return data to the frontend
Then in the frontend, your Angular app, you can execute a get request to this /api/animals/cow
url of your django app and retrieve the data for a cow from the external provider without exposing your API_KEY.
So the flow would be like this:
Angular requests data from Django, Django gets that data from the external provider, does some data processing if required and then returns that data to Angular. You do not have to store anything in the database (but you can of course do it or for example log things, it's optional).
Upvotes: 1