Now that we have created our API view we can go ahead and add a serializer to our
view a serializer is a feature from the Django rest framework that allows you to
easily convert data inputs into Python objects and vice versa it's kind of
similar to a django form which you define and it has the various fields
that you want to accept for the input for your api so if we're going to add
post or update functionality to our hello API view then we need to create a
serializer to receive the content that we post to the API let's go ahead
and create the sterilizer for our profiles API project
Create a new file
inside our profiles API app and call it serializers dot py
It's good practice to
keep all of your sterilizers for your app in a single file called serializers
so you know where to look if you ever need to find them we're going to start
by including the serializers import from the Django rest framework so type
from rest underscore framework import serializers then we're going to create a
new class called hello serializer and we're going to base it on the serializer
class from the Django rest framework so type class
hello serializer and then in the base class we're going to
type serializers dot serializer and the second one is the class name so it's got
a capital S
Okay then put a dock string under the class declaration called and
write serializes a name field for testing our
API view
What we're going to do is we're going to create a simple serializer that
accepts a name input and then we're going to add this to our API view and
we're going to use it to test the post functionality of our API view
serializers function very similar to Django forms if you've
ever used them if you haven't use them don't worry they're quite simple to get
your head around all you do is you define the serializer and then you
specify the fields that you want to accept in your serializer input so we're
going to create a field called name and this is a value that can be passed into
the request that will be validated by the serializer
So sterilizers also take
care of validation rules so if you want to say you want to accept a certain
field of a certain type serializers will make sure that the content past that api
is of the correct type that you want to require for that field
So let's define a
new field which is a character field for a name input so type name equals
serializers dot char field and then we need to pass in a maximum length
argument like max length equals 10
what this does is it creates a new name
field on our serializers which is a character field that allows you to input
any text that you can input on the computer and it gives it a maximum
length of 10 so it will accept any character inputs
that are 10 or less characters
Okay so save that file and that's how
you create a serializer with the Django rest framework