Since your question not mentioning anything about writing data into DB, undoubtedly you can go with Method-1.
Let's look into this sample api, which return a list of items (a list api).
Case - 1 : We need show the same response as we got from third-party api
In that case, we don't need any serializer or serialization process, all we need is pass the data from third-party API to the client.
from rest_framework.decorators import api_view
from rest_framework.response import Response
import requests
@api_view()
def my_view(request):
tp_api = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(tp_api)
return Response(data=response.json())
Case - 2 : If you don't need complete data, but few parts (id and body)
In this particular situation, you can go with pythonic loop or DRF serializer.
# using DRF serializer
from rest_framework import serializers
# serializer class
class Myserializer(serializers.Serializer):
id = serializers.CharField()
body = serializers.CharField()
@api_view()
def my_view(request):
tp_api = "https://jsonplaceholder.typicode.com/posts"
response_data = requests.get(tp_api).json()
my_serializer = Myserializer(data=response_data, many=True)
my_serializer.is_valid(True)
return Response(data=my_serializer.data)
#Python loop way
@api_view()
def my_view(request):
tp_api = "https://jsonplaceholder.typicode.com/posts"
response_data = requests.get(tp_api).json()
data = [{"id": res['id'], "body": res['body']} for res in response_data]
return Response(data=data)
In case-2, I would reccomend to use DRF serializer, which does lots of things like validation, etc
When coming into your second approch, doing validation of the input data would depends on your requirement. As you said in comments, you need to provide some inputs to the third-party api. So, the validation should be carried out before accessing the third-party api
# Validation example
class MyInputSerializer(serializers.Serializer):
postId = serializers.IntegerField(max_value=10)
class MyOutputSerializer(serializers.Serializer):
id = serializers.CharField()
body = serializers.CharField()
@api_view()
def my_view(request):
input = MyInputSerializer(data=request.GET)
input.is_valid(True)
tp_api = "https://jsonplaceholder.typicode.com/comments?postId={}".format(input.data['postId'])
response_data = requests.get(tp_api).json()
my_serializer = MyOutputSerializer(data=response_data, many=True)
my_serializer.is_valid(True)
return Response(data=my_serializer.data)
Conclusion
The DRF is flexible enough to get desired output format as well as taking data into the system. In short, It all depends on your requirements