I have a user API that I have prepared with django. However, when I make API requests with the Postman application for testing purposes, I get a 400 Bad Request warning, what could be the reason? I can write all of my codes as follows if there is any other required code.
This is views.py code
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import CustomUserSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.permissions import AllowAny
class CustomUserCreate(APIView):
permission_classes = [AllowAny]
def post(self, request, format='json'):
serializer = CustomUserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
if user:
json = serializer.data
return Response(json, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class BlacklistTokenUpdateView(APIView):
permission_classes = [AllowAny]
authentication_classes = ()
def post(self, request):
try:
refresh_token = request.data["refresh_token"]
token = RefreshToken(refresh_token)
token.blacklist()
return Response(status=status.HTTP_205_RESET_CONTENT)
except Exception as e:
return Response(status=status.HTTP_400_BAD_REQUEST)
This is my urls
api/urls.py
from django.urls import path
from .views import CustomUserCreate, BlacklistTokenUpdateView
app_name = 'users'
urlpatterns = [
path('create/', CustomUserCreate.as_view(), name="create_user"),
path('logout/blacklist/', BlacklistTokenUpdateView.as_view(),
name='blacklist')
]
core/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('admin/', admin.site.urls),
path("api/post/", include("post.api.urls", namespace="post")),
path("api/post/audio/", include("post_audio.api.urls", namespace="postaudio")),
path('api/comment/', include('comment.api.urls', namespace='comment')),
path("api/categories/", include("post.api.urls", namespace="categories")),
path("api/author/", include("author.api.urls", namespace="author")),
path("api/favourites/", include("favourite.api.urls", namespace="favourite")),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
] static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And Also this is my serializers.py code
from rest_framework import serializers
from users.models import NewUser
class CustomUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
user_name = serializers.CharField(required=True)
password = serializers.CharField(min_length=8, write_only=True)
class Meta:
model = NewUser
fields = ('email', 'user_name', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password', None)
# as long as the fields are the same, we can just use this
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
CodePudding user response:
From what I've seen, you can get bad requests from two places: CustomUserCreate
and BlacklistTokenUpdateView
.
To help you debugging this you could add logs including serializer.errors
(in CustomUserCreate
) and inside the except in BlacklistTokenUpdateView
. A good practice is avoid catching generic exceptions. This way you'll know exactly why it failed.
CodePudding user response:
according to your code class "CustomUserCreate" retruns 400 error if "serializer.is_valid()" returns false, I think you are not sending required Parametrs inside body of Postman.
in case of class "BlacklistTokenUpdateView" also returns 400 error if any Exception has occurred
CodePudding user response:
Can you include information about the postman call(s) that you are making? A 400 error would likely suggest that the issues lies with something about how you've constructed the requests from that tool. Please send any headers, body and the full URI. You can export from the postman console...
The email value you are sending is not a valid email format and you also don't appear to be be sending a user_name, so I suspect that the requests are failing validation at the serializer level.