User API Resource

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

I want to expose our new User entity as an API resource. And we know how to do that! Add... @ApiResource!

... lines 1 - 4
use ApiPlatform\Core\Annotation\ApiResource;
... lines 6 - 8
/**
* @ApiResource()
... line 11
*/
class User implements UserInterface
... lines 14 - 128

Just like that! Yes! Our API docs show one new resource with five new endpoints, or operations. And at the bottom, here's the new User model.

Hmm, but it's a bit strange: both the hashed password field and roles array are part of the API. Yea, we could create a new user right now and pass whatever roles we think that user should have! That might be ok for an admin user to be able to do, but not anyone. Let's take control of things.

UUID's?

Oh, one thing I want you to notice is that, so far, the primary key is always being used as the "id" in our API. This is something that's flexible in API Platform. In fact, instead of using an auto-increment id, one option is to use a UUID. We're not going to use them in this tutorial, but using a UUID as your identifier is something that's supported by Doctrine and API Platform. UUIDs work with any database, but they are stored more efficiently in PostgreSQL than MySQL, though we use some UUID's in MySQL in some parts of SymfonyCasts.

But... why am I telling you about UUID's? What's wrong with auto-increment ids? Nothing... but.... UUID's may help simplify your JavaScript code. Suppose we write some JavaScript to create a new CheeseListing. With auto-increment ids, the process looks like this: make a POST request to /api/cheeses, wait for the response, then read the @id off of the response and store it somewhere... because you'll usually need to know the id of each cheese listing. With UUID's, the process looks like this: generate a UUID in JavaScript - that's totally legal - send the POST request and... that's it! With UUID's, you don't need to wait for the AJAX call to finish so you can read the id: you created the UUID in JavaScript, so you already know it. That is why UUID's can often be really nice.

To make this all work, you'll need to configure your entity to use a UUID and add a setId() method so that it's possible for API Platform to set it. Or you can create the auto-increment id and add a separate UUID property. API Platform has an annotation to mark a field as the "identifier".

Normalization & Denormalization Groups

Anyways, let's take control of the serialization process so we can remove any weird fields - like having the encoded password be returned. We'll do the exact same thing we did in CheeseListing: add normalization and denormalization groups. Copy the two context lines, open up User and paste. I'm going to remove the swagger_definition_name part - we don't really need that. For normalization, use user:read and for denormalization, user:write.

... lines 1 - 9
/**
* @ApiResource(
* normalizationContext={"groups"={"user:read"}},
* denormalizationContext={"groups"={"user:write"}},
* )
... line 15
*/
class User implements UserInterface
... lines 18 - 135

We're following the same pattern we've been using. Now... let's think: what fields do we need to expose? For $email, add @Groups({}) with "user:read", "user:write": this is a readable and writable field. Copy that, paste above password and make it only user:write.

... lines 1 - 7
use Symfony\Component\Serializer\Annotation\Groups;
... lines 9 - 16
class User implements UserInterface
{
... lines 19 - 25
/**
... line 27
* @Groups({"user:read", "user:write"})
*/
private $email;
... lines 31 - 36
/**
... lines 38 - 39
* @Groups({"user:write"})
*/
private $password;
... lines 43 - 133
}

This... doesn't really make sense yet. I mean, it's not readable anymore, which makes perfect sense. But this will eventually store the encoded password, which is not something that an API client will set directly. But... we're going to worry about all of that in our security tutorial. For now, because password is a required field in the database, let's temporarily make it writable so it doesn't get in our way.

Finally, make username readable and writable as well.

... lines 1 - 16
class User implements UserInterface
{
... lines 19 - 43
/**
... line 45
* @Groups({"user:read", "user:write"})
*/
private $username;
... lines 49 - 133
}

Let's try it! Refresh the docs. Just like with CheeseListing we now have two models: we can read email and username and we can write email, password and username.

The only other thing we need to make this a fully functional API resource is validation. To start, both $email and $username need to be unique. At the top of the class, add @UniqueEntity() with fields={"username"}, and another @UniqueEntity() with fields={"email"}.

... lines 1 - 6
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
... lines 8 - 11
/**
... lines 13 - 16
* @UniqueEntity(fields={"username"})
* @UniqueEntity(fields={"email"})
... line 19
*/
class User implements UserInterface
... lines 22 - 142

Then, let's see, $email should be @Assert\NotBlank() and @Assert\Email(), and $username needs to be @Assert\NotBlank(). I won't worry about password yet, that needs to be properly fixed anyways in the security tutorial.

... lines 1 - 9
use Symfony\Component\Validator\Constraints as Assert;
... lines 11 - 20
class User implements UserInterface
{
... lines 23 - 29
/**
... lines 31 - 32
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;
... lines 37 - 49
/**
... lines 51 - 52
* @Assert\NotBlank()
*/
private $username;
... lines 56 - 140
}

So, I think we're good! Refresh the documentation and let's start creating users! Click "Try it out". I'll use my real-life personal email address: cheeselover1@example.com. The password doesn't matter... and let's make the username match the email without the domain... so I don't confuse myself. Execute!

Woohoo! 201 success! Let's create one more user... just to have some better data to play with.

Failing Validation

Oh, and what if we send up empty JSON? Try that. Yea! 400 status code.

Ok... we're done! We have 1 new resource, five new operations, control over the input and output fields, validation, pagination and we could easily add filtering. Um... that's amazing! This is the power of API Platform. And as you get better and better at using it, you'll develop even faster.

But ultimately, we created the new User API resource not just because creating users is fun: we did it so we could relate each CheeseListing to the User that "owns" it. In an API, relations are a key concept. And you're going to love how they work in API Platform.

Leave a comment!

  • 2020-03-28 Diego Aguiar

    Hmm, that's odd. If you persist an User with an empty array in its roles property, it should store a json like this <code[]< code=""> and that's not considered as empty for a Database

  • 2020-03-27 Thomas Castangia

    Yes i have check this. To solve i have modify this in the db ALTER TABLE `user` CHANGE `roles` `roles` TEXT NULL.

    My code was :
    /*
    *
    * @ORM\Column(type="json")
    */
    private $roles = [];

  • 2020-03-27 Diego Aguiar

    Hey Thomas Castangia

    That's odd. Can you double-check that your `roles` property is initially set to an empty array?


    // User.php

    private $roles = [];

    Cheers!

  • 2020-03-26 weaverryan

    Hey @Szabo!

    This *should* be possible, but it would be a PUT request. It's an HTTP "spec" thing - if you're creating an object but *providing* the primary key, then the proper HTTP method is PUT. Try PUT and let me know if it works.

    Cheers!

  • 2020-03-26 Thomas Castangia

    Hello everyone,

    when i post new user return error 500 with message "General error: 1364 Field 'roles' doesn't have a default value" but my code is the same as eample code. What is wrong?

  • 2020-03-25 Szabo

    Hello,
    It is possible to make a post request providing the primary key value too?
    e.g.


    {
    id: 1,
    name: "Szabo"
    }


    I ask because when I try to make the post I get
    {
    "code": 500,
    "message": "Update is not allowed for this operation."
    }

  • 2020-03-18 Diego Aguiar

    Hey man,

    Good observation. Hashing the password and adding roles is a job you have to do and has nothing to do with ApiPlatform. Ryan talks more about that in the next course: https://symfonycasts.com/sc...

    About the id thing. How's your configuration? If you are using UUID's then it should be totally different than an auto-incremented id

    Cheers!

  • 2020-03-16 mad joe

    Hi everyone!
    I thought everyting was undercontrole util I saw in my Mysql database two things:
    - the password hasen't been hashed
    - no role has been set too

    And one question: is it normal that the id inserted has no change compare to an normal autoIncrement, what the difference of having the UUID orientation ? '

    I post my new user thanks to the api_doc via the POST tab

    thank you for any return which can light this up

  • 2020-01-23 weaverryan

    Hey AdamDocherty!

    Good job finding the solution! Like all errors, it's a tough error the first time you see it - hopefully it won't be next time! Our code *does* have this use statement, but you're right that you don't see it in the video. The reason is that we *often* allow classes (or annotations) to auto-complete in PhpStorm. When we do this, it automatically adds the use statement needed on top (you need the php-annotations plugin installed for this to work with annotations). I try to mention that this is happening from time-to-time... but if I mention it *every* time, it gets laborious. It's a tricky balance :/. But now that you know it, I think you should be good. If you ever have some mysterious problem, you can also expand the full code block below the video and see *exactly* what our code looks like.

    Cheers!

  • 2020-01-23 AdamDocherty

    I am sure I am doing something stupid, but I am getting this error when adding the groups annotation to the email property in the user entity...

    [Semantical Error] The annotation "@Groups" in property App\Entity\User::$email was never imported. Did you maybe forget to add a "use" statement for this annotation?

    Solution:

    as per
    https://api-platform.com/do...

    # api/config/packages/framework.yaml
    framework:
    serializer: { enable_annotations: true }

    #in your user entity
    use Symfony\Component\Serializer\Annotation\Groups;

    #and you will need this later...
    use Symfony\Component\Validator\Constraints as Assert;

    This had me stumped for awhile as it is not evident in the tutorial video... maybe a good idea to update this considering it is paid for (well I paid for it). Or it could be that I missed some kind of importation at the start of things...

  • 2019-11-11 Codsworth

    Thanks Vladimir,

    I'll give that a try!

  • 2019-11-11 Vladimir Sadicov

    Hey @Codsworth

    You can try pecl install libsodium just be sure that brew installed php is fully configured

    Cheers

  • 2019-11-10 Codsworth

    Hey, I get the error below when selecting Argon2i. How can I get around it? Running a mac with brew installed php.

    Argon2i algorithm is not supported. Install the libsodium extension or use BCrypt instead.

  • 2019-10-13 Benjamin Quarta

    Yeah, that would be even easier :D

  • 2019-10-13 Egor Ushakov

    ... or just @Orm\Table(name=“users”). I mostly like name table with plurals.

  • 2019-10-12 Benjamin Quarta

    Hello everyone,
    a quick "heads up" when you're using PostgreSQL. Since Ryan is talking about some benefits of using UUIDs you should mention that in Postgres "user" is a reserved word ;) ... If you don't want to run into an Error 500 when trying to create a User please add the following line to your Entity:
    @Orm\Table("`user`")

    This will escape the word in your SQL-Statements and you should be fine :)

    best regards
    Ben