如何将json数据渲染到restapi中?

时间:2019-05-25 19:51:10

标签: django django-rest-framework

我从某些URL得到JSON响应。我必须将其显示到rest api中,但出现错误。这是我的代码

观看次数

class StoreView(APIView):
    serializer_class = PostcodeLookupSerializer
    resp = requests.get('https://api.postcodes.io/postcodes/BN14 9GB')
    resp_data = resp.json()['result']
    result_dic = {
        'longitude': resp_data['longitude'],
        'latitude': resp_data['latitude']
    }
    result_data = JsonResponse(result_dic)

    def result(self):
        json_data = self.resp_data()
        file_serializer = PostcodeLookupSerializer(json_data, many=True)
        return Response(data=file_serializer.data, status=status.HTTP_200_OK)

序列化器

class PostcodeLookupSerializer(serializers.Serializer):
    postcode = serializers.CharField(required=True)
    name = serializers.CharField(required=True)

和网址

urlpatterns = [
path('views/', StoreView.as_view(), name='postcode_lookup'),]

如何在restapi中显示json响应? 我收到此错误

"detail": "Method \"GET\" not allowed."

1 个答案:

答案 0 :(得分:0)

您应该在响应内返回数据,如下所示:

返回响应(数据= file_serializer.data,状态=状态。HTTP_200_OK)