0

Besides the API I created by using the django rest framework, now I want to add the existing commerial API into the backend, how to do this?

The commerial API include several part(API), for example, /prepare, /upload, /merge,/get_result, etc. They all use the "POST" indeed.

Do I need to call the commerial API directly on the frontend? Or I need to integrate the commerial API in to one backend API? Any suggestions are appreciated.Thanks.

For example:

  ```
  class TestView(APIView):
         """
         Add all the commerial API here in order
             /prepare(POST)
             /upload(POST)
             /merge(POST)
             /get_result(POST)
         return Result
         """
  ```

1 Answer 1

1

Depending on your needs, I suggest making the external API calls on backend.

As a good practice, you should seperate your external API calls from your views. As it can be messy as the project gets bigger.

Check the sample code of how I manage external API calls, by seperating them to a different file, for example api_client.py

My default api_client.py looks something like this. (You need to install "requests" pip package by pip install requests)

import requests
from django.conf import settings

class MyApiClient(object):
    def __init__(self):
        self.base_url = settings.EXTERNAL_API_1.get('url')
        self.auth_url = "{0}login/".format(self.base_url)
        self.username = settings.EXTERNAL_API_1.get('username')
        self.password = settings.EXTERNAL_API_1.get('password')
        self.session = None
        self.access_token = None
        self.token_type = None
        self.token_expires_in = None

    def _request(self, url, data=None, method="POST", as_json=True):
        if self.session is None:
            self.session = requests.Session()

        if not self.access_token:
            self.authenticate()

        r = requests.Request(method, url=url, data=data, headers={
            "Accept": "application/json",
            "Content-Type": "application/json",
            'Authorization': 'Token {0}'.format(
            self.access_token)
        })

        prepared_req = r.prepare()

        res = self.session.send(prepared_req, timeout=60)

        if as_json:
            json_result = res.json()
            return json_result
        return res

    def _get(self, url):
        return self._request(url=url, method="GET")

    def _post(self, url, data):
        return self._request(url=url, data=data, method="POST")

    def authenticate(self):
        res = requests.post(self.auth_url, json={'username': self.username,
                                             'password': self.password},
                        headers={"Content-Type": "application/json"})
        if res.status_code != 200:
            res.raise_for_status()

        json_result = res.json()
        self.access_token = json_result.get('response', None).get('token',None)

    def prepare(self):
        something = 'bla bla'
        request_url = "{0}prepare".format(self.base_url)
        result = self._post(url=request_url, data=something)
        return result

And in your views.py

from api_client import MyApiClient

class TestView(APIView):
    api_client = MyApiClient()

    def post(request, *args, **kwargs):
        res1 = api_client.prepare()
        res2 = api_client.your_other_method()
        res3 = api_client.your_last_method()
        return Response(res3)

Edited! Hope this helps now :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot engin_opek. I will try your suggestions. One more question, it seems your code not related to django rest framework? For example, how to design the url of your sample code?How to call from frontend? Thanks a lot, a little new to this area. For example, url of drf : path('', include(router.urls)),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.