This is a continuation of the part one post found here
My IDE
Since I build all my new projects in SPA style with Symfony/api-platform backend, I find it helpful to separate my IDEs. I guess this is not ideal, because each IDE has its own style shortcuts… but I have my PHP workflow in PHPStorm, and my Javascript/HTML workflow in VS Code
In the previous part we launched our app with the symfony binary
symfony serve
Now our API will be listening on http://127.0.0.1:8000
Installing maker is a nice easy way to build your entities, and also immediately expose the API.
composer require maker --dev
I wish there was a nice JWT login scaffold available for API platform, but there isn’t. So, my next step is to create the user in Symfony
symfony console make:user
Then make a controller for managing login and registraion. This would be a normal Controller responding in JSON.
Start by making the controller
symfony console make:controller UserController
I use something like the following in mine
<?php namespace App\Controller; use App\Entity\User; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; class SecurityController extends AbstractController { /** * @Route("/login", name="app_login", methods={"POST"}) */ public function login() { return $this->json([ 'user' => $this->getUser() ? $this->getUser()->getId() : null] ); } /** * @Route("/register", name="app_register", methods={"POST"}) */ public function register(Request $request,UserPasswordEncoderInterface $encoder, EntityManagerInterface $entityManager,ValidatorInterface $validator) { $user = new User(); $user->setEmail($data['email']); $user->setPassword($encoder->encodePassword($user, $data['plainPassword'])); $entityManager->persist($user); $entityManager->flush(); return new JsonResponse($user); } }
The you’ll need to install the bundle for managing JWT. The instructions are a bit detailed, so get it from the source
Your API is almost ready to go, just make a entity to automatically expose the API.
symfony console make:entity
Now you are well on your way, register, login, and an exposed entity.
You can view your API at https://127.0.0.1:8000/api/docs and if you password protext it, use a tool like postman to login and get a token, so you can authorize and test your API via the docs.
Then you need a front end…