Stream Our Mistakes EP 003
\n
\nIn this episode, we will be working creating a REST API endpoint using Django REST Framework. This will be a multi part series as I plan to use this backend with a Xamarin Android application. No guarantees it is going to work but I will attempt it anyways. This podcast/blog isn't called stream our mistakes for nothing aye?
\n\n\n
\nI looked over a few youtube videos, this blog post and the excellent Django Rest Documentation.
\n
\nSince this repo is not public, here is the code snippets that are relevant to the video.
\nPlease note: This project assumes you have already implemented Django Rest Framework in your project.
\n
\nIn the Serializers.py file:
\n\n\n
1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n
from rest_framework import serializer\n from django.contrib.auth.models import User\n \n class UserCreateSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ('first_name',\n 'last_name',\n 'email',\n 'password',)\n extra_kwargs = {'password': {'write_only': True} }\n \n # override create function \n def create(self, validated_data):\n username = validated_data['email']\n email = validated_data['email']\n first_name = validated_data['first_name']\n last_name = validated_data['last_name']\n password = validated_data['password']\n # I want to set the email as the username so this new object reflects that. \n newUser = User(\n username = email,\n first_name = first_name,\n last_name = last_name,\n email = email,\n password = password)\n newUser.set_password(password)\n newUser.save()\n #return super().create(validated_data) \n return validated_data\n\n\n\n\n
1\n2\n3\n4\n
# view \nclass UserCreateAPIView(CreateAPIView):\n serializer_class = UserCreateSerializer\n returnAllUsers = User.objects.all()\n\n\n\n\n
1\n2\n3\n4\n
# urls\nfrom app.serializers import UserCreateAPIView\n \n url(r'^api/register/$', app.views.UserCreateAPIView.as_view()), \n\n\n\n\n
1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n
INSTALLED_APPS = [\n # Add your apps here to enable them \n 'app',\n 'rest_framework',\n # default \n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n \n]\n\n# currently leaving the permissions open.\n# in the next episodes, I'll be updating this with token authetication.\nREST_FRAMEWORK = {\n'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),\n\n}\n\n\n\n\n