Home > Software engineering >  Symfony with API Platform Form and controller
Symfony with API Platform Form and controller

Time:09-14

I have started a Symfony 6 project using the classic RegitrationController (that inherits from AbstractController), RegistrationFormType and User entity obtained from:

symfony console make:registration-form

I can now create a user through the form that adds a new entity in my database.

I also wanted to create an API using API Plateform. I have then added a couple modifications to my User schema and the API is working, I can create a user through the API too.

I now wonder how to properly couple the form/controller and the API. Indeed, in order not to have redondant code and use the same User schema, I would like to find a way that my RegistrationFormType works with the API. Also note that on the one hand I have code in my RegitrationController that, e.g., hashes the user password before saving it to the database. On the other hand this is achieved by a UserDataPersister on the API side.

What is the good practice to factorize that code and structure my architecture in order to be able to create users from both the form and the API? (I would like to keep the cool things that the Symfony AbstractController provides like createForm, handleRequest, renderForm, etc.)

I cannot find examples using both Form/Controller and API Plateform.

Is it a bad idea to have the Form/Controller and API in the same project?

CodePudding user response:

When it comes to switching to API Platform, you first have to unlearn what you have learned with more traditional apps :)

Things like creating/rendering forms, and handing requests, are possible, BUT keep in mind that your API accepts, among others, the application/json and not the application/x-www-form-urlencoded.

It all really depends on your choice of client-side code. If you stick to more traditional forms with no React, Angular, or Vue, you send the data in application/x-www-form-urlencoded and your API Platform needs a way to denormalize that.

There is an official article on that topic: https://api-platform.com/docs/core/form-data/, but it has its own perks (such as CSRF handling)

A more common approach is to create a form entirely from scratch using some modern JS framework and just submit the object (in JSON format)

  • Related