Как получить данные из внешнего API в Django Rest Framework

Я создаю DRF проект (только API), где вошедший пользователь может указать, сколько чужих случайно сгенерированных учетных данных он хочет получить.

Вот моя проблема: Я хочу получить эти учетные данные из внешнего API (https://randomuser.me/api). Этот сайт генерирует данные случайных пользователей в количестве, указанном в параметре url "results". Например. https://randomuser.me/api/?results=40

Мой вопрос:

Как я могу получить эти данные? Я знаю, что метод JavaScript fetch() может быть полезен, но я не знаю, как соединить его с Django Rest Framework, а затем манипулировать им. Я хочу показать данные пользователю после того, как он отправит POST-запрос (указав только количество пользователей, которых нужно сгенерировать), а также сохранить результаты в базе данных, чтобы он мог получить к ним доступ позже (через GET-запрос).

Если у вас есть какие-либо идеи или советы, я буду очень благодарен.

Спасибо!

Вот как можно сделать вызов API в представлении API Django Rest Framework:

Поскольку вы хотите хранить внешний запрос API в базе данных. Это пример модели для хранения результата пользователя.

models.py

from django.conf import settings

class Credential(models.Models):
    """ A user can have many generated credentials """
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    value = models.CharField()

    # Here we override the save method to avoid that each user request create new credentials on top of the existing one
    
    def __str__(self):
        return f"{self.user.username} - {self.value}"

views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
# Assume that you have installed requests: pip install requests
import requests
import json

class GenerateCredential(APIVIew):
    """ This view make and external api call, save the result and return 
        the data generated as json object """
    # Only authenticated user can make request on this view
    permission_classes = (IsAuthenticated, )
    def get(self, request, format=None):
        # The url is like https://localhost:8000/api/?results=40
        results = self.request.query_params.get('type')
        response = {}
        # Make an external api request ( use auth if authentication is required for the external API)
        r = requests.get('https://randomuser.me/api/?results=40', auth=('user', 'pass'))
        r_status = r.status_code
        # If it is a success
        if r_status = 200:
            # convert the json result to python object
            data = json.loads(r.json)
            # Loop through the credentials and save them
            # But it is good to avoid that each user request create new 
            # credentials on top of the existing one
            # ( you can retrieve and delete the old one and save the news credentials )
            for c in data:
                credential = Credential(user = self.request.user, value=c)
                credential.save()
            response['status'] = 200
            response['message'] = 'success'
            response['credentials'] = data
        else:
            response['status'] = r.status_code
            response['message'] = 'error'
            response['credentials'] = {}
        return Response(response)


class UserCredentials(APIView):
    """This view return the current authenticated user credentials """
    
    permission_classes = (IsAuthenticated, )
    
    def get(self, request, format=None):
        current_user = self.request.user
        credentials = Credential.objects.filter(user__id=current_user)
        return Response(credentials)

NB : Эти представления предполагают, что user, который делает запрос, аутентифицирован, больше информации здесь. Поскольку нам нужно, чтобы пользователь сохранил полученные учетные данные в базе данных.

urls.py

path('api/get_user_credentials/', views.UserCredentials.as_view()),
path('api/generate_credentials/', views.GenerateCredentials.as_view()),

.js

const url = "http://localhost:8000/api/generate_credentials/";
# const url = "http://localhost:8000/api/get_user_credentials/";

fetch(url)
.then((resp) => resp.json())
.then(function(data) {
    console.log(data);
})
.catch(function(error) {
    console.log(error);
});
Вернуться на верх