0

Basically, I have this API end point that will be called if you make a POST request to it. The problem is for some reason, I can't convert the bytes to JSON so I can access the data.

My code:

@api_view(['POST'])
def create_user(request):
    """ POST = Create user. """
    # Check that a username with this email doesn't already exist
    try:
        data = {}
        print("IS IT WORKING...?")
        print(type(request.body))
        print(request.body)
        # Use double quotes to make it valid JSON
        my_json = request.body.decode('utf8').replace("'", '"')
        print("MY_JSON:")
        print(my_json)
        data = json.loads(my_json)
        print("DATA:")
        print(data)
        s = json.dumps(data, indent=4, sort_keys=True)
        print("s:")
        print(s)
    except User.DoesNotExist:
        print("PLS WORK ON CONSOLE")
    return Response(status=status.HTTP_409_CONFLICT)

I try to make a POST request to my path users/create/ using Postman, but when I print request.body to see the contents of my POST request, it is formatted incorrectly with a lot of random numbers and dashes. This is preventing me from converting it to JSON. It's a simple POST request with email and password fields.

This is what the weird formatting looks like: https://gyazo.com/fa1cc2f04637c02f79fe59790153ae40

This is what the "json" looks like after I have decoded it and converted with double quotes (Notice the weird dashes and numbers): https://gyazo.com/3ca41106117a4e9acdd96929469313a1

After that, it ERRORS because of the data = json.loads(my_json) because the input is incorrectly formatted.

Error message:

Internal Server Error: /users/create/
Traceback (most recent call last):
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/mightu/Desktop/jason_app/env/lib/python3.7/site-packages/rest_framework/decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "/Users/mightu/Desktop/jason_app/users/views.py", line 38, in create_user
    data = json.loads(my_json)
  File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I've used these SO posts (1, 2) to get me to where I am now (realizing my input is just wrong!).

MyNameIsCaleb
  • 4,409
  • 1
  • 13
  • 31
Jessica
  • 1,083
  • 2
  • 12
  • 27
  • 1
    Hi, if this question was in error (typo or simple mistake) please delete it. If not but you have an answer, please post your answer as an answer to your own question and select it with the checkmark. – MyNameIsCaleb Oct 21 '19 at 20:53
  • 1
    Thank you, I will do that (you're right). :) I can only accept my own answer after 2 days! – Jessica Oct 21 '19 at 20:56
  • You could try setting the `Content-Type` header on the POST request to `application/json; charset=utf-8`. That _should_ encode the json correctly. – snakecharmerb Oct 22 '19 at 04:31

1 Answers1

0

EDIT: OK SO I FOUND THE SOLUTION. In Postman, you can send data as form-data and also as raw. I was using form-data and I guess that just ruined everything and created all the weird -----'s and integers. I switched to raw and directly typed the JSON formatting and my code NOW WORKS! All of it! But I totally don't understand why. I just had a hunch that the method I was sending data was simply incorrect. Can someone explain?

Jessica
  • 1,083
  • 2
  • 12
  • 27