Getting Started with Building APIs in Symfony2

来源:互联网 时间:1970-01-01

Hello all you Interwebs friends!While we’re passing through the shallow mists of time, RESTis becoming more and more of a universal standard when building web applications. That said, here’s a very brief tutorial on how to get started with building APIs in Symfony2.

Spoiler alert:the bits of code written below useFosUserBundle + Doctrine.

1.Generate a New Bundle

It’s nice to keep your code neat and tidy, so ideally, you should create a separate bundle that will only store your API code, we can generically name ApiBundle.

$ php app/console generate:bundle --bundle-name=ApiBundle --format=annotation $phpapp/consolegenerate:bundle--bundle-name=ApiBundle--format=annotation 2.Versioning

This isn’t by any means mandatory, but if you believe that your API endpoints will suffer major changes along the way, that cannot be predicted from the get go, it would be nice to version your code. This means that you would, initially, have a prefix in your endpoints, like: /v1/endpoint.json, and you’d increase that value each time a new version comes along. I’ll describe how to actuallycreate the first version ( v1) of your API a little furtherdown the line.

3.Install a Few Useful Bundles FosRestBundle – this bundle will make our REST implementation a lot easier. $ composer require friendsofsymfony/rest-bundle $composerrequirefriendsofsymfony/rest-bundle

and then include FOSRestBundlein your AppKernel.phpfile:

$bundles = array(// FOS/RestBundle/FOSRestBundle(),); $bundles=array( // ...newFOS/RestBundle/FOSRestBundle(),); JmsSerializerBundle – this will take care of the representation of our resources, converting objects into JSON. composer require jms/serializer-bundle composer requirejms/serializer-bundle

and then include JMSSerializerBundlein your AppKernel.php:

$bundles = array(// JMS/SerializerBundle/JMSSerializerBundle(),// ...); $bundles=array(// ...newJMS/SerializerBundle/JMSSerializerBundle(),// ...); 4.Configurations

Configurethe Response object to return JSON, as well as set a default format for our API calls. This can be achieved byadding the following code in app/config/config.yml:

fos_rest: format_listener: rules: - { path: ^/api/, priorities: [ html, json, xml ], fallback_format: ~, prefer_extension: true } routing_loader: default_format: json param_fetcher_listener: true view: view_response_listener: 'force' formats: xml: true json: true templating_formats: html: true fos_rest:format_listener: rules: -{path:^/api/,priorities:[html,json,xml],fallback_format:~,prefer_extension:true}routing_loader:default_format:jsonparam_fetcher_listener:trueview:view_response_listener:'force'formats:xml:truejson:truetemplating_formats:html:true 5.Routing

I prefer using annotations as far as routes go, so all we need to do in this scenario would be to modifyour API Controllers registration in /app/config/routing.yml. This registration should have already been created when you ran the generate bundle command. Now we’ll only need to add our version to that registration.As far as the actual routes of each endpoint go, we’ll be manually defining themlater on, in each action’s annotation.

api: resource: "@ApiBundle/Controller/V1/" type: annotation prefix: /api/v1 api: resource:"@ApiBundle/Controller/V1/" type:annotation prefix:/api/v1

At this point we’re all set to start writing our first bit of code. First off, in our Controller namespace, we would want to create a new directory, called V1. Thiswill hold all of our v1 API Controllers. Whenever we want to create a new version, we’ll start from scratch by creating a V2namespace and so on.

After that’s done let’s create an action that will GETa user (assuming we’ve previously created a User entity and populated it with users). This would look something like:


<?php namespace ApiBundle/Controller/V1; use FOS/RestBundle/Controller/FOSRestController; use FOS/RestBundle/Controller/Annotations as Rest; class UserController extends FOSRestController { /** * @return array * @Rest/Get("/users/{id}") * @Rest/View */ public function getUserAction($id) { $em = $this->getDoctrine()->getManager(); $user = $em->getRepository('AppBundle:User')->find($id); return array('user' => $user); }} <?php namespaceApiBundle/Controller/V1; useFOS/RestBundle/Controller/FOSRestController; useFOS/RestBundle/Controller/AnnotationsasRest; classUserControllerextendsFOSRestController { /** * @return array * @Rest/Get("/users/{id}") * @Rest/View */ publicfunctiongetUserAction($id) { $em=$this->getDoctrine()->getManager(); $user=$em->getRepository('AppBundle:User')->find($id); returnarray('user'=>$user); }}

If we want to GET a list of all users, that’s pretty straightforward as well:


/** * GET Route annotation. * @return array * @Rest/Get("/users/get.{_format}") * @Rest/View */public function getUsersAction(){ $em = $this->getDoctrine()->getManager(); $users = $em->getRepository('AppBundle:User')->findAll(); return array('users' => $users);} /** * GET Route annotation. * @return array * @Rest/Get("/users/get.{_format}") * @Rest/View */publicfunctiongetUsersAction(){ $em=$this->getDoctrine()->getManager(); $users=$em->getRepository('AppBundle:User')->findAll(); returnarray('users'=>$users);}

With that done, when running a GET request on, you should get a jsonresponse withthat specific user object.

What about a POST request? Glad you asked!There are actually quite a few options to do that. One would be to get the request data yourself,validate it and create the new resource yourself. Another (simpler) option would be to use Symfony Formswhich would handle all this for us.

Thescenario here would be for us to add a new user resource into our database.

If you’re also using FosUserBundleto manage your users, you can just use a similarRegistrationFormType:


<?php namespace ApiBundle/Form/Type; use Symfony/Component/Form/AbstractType; use Symfony/Component/Form/FormBuilderInterface; use Symfony/Component/OptionsResolver/OptionsResolver; class RegistrationFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('email', 'email') ->add('username') ->add('plainPassword', 'password') ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle/Entity/User', 'csrf_protection' => false )); } public function getName() { return 'my_awesome_form'; }} <?php namespaceApiBundle/Form/Type; useSymfony/Component/Form/AbstractType; useSymfony/Component/Form/FormBuilderInterface; useSymfony/Component/OptionsResolver/OptionsResolver; classRegistrationFormTypeextendsAbstractType { publicfunctionbuildForm(FormBuilderInterface$builder,array$options){ $builder ->add('email','email') ->add('username') ->add('plainPassword','password');}publicfunctionconfigureOptions(OptionsResolver$resolver){$resolver->setDefaults(array('data_class'=>'AppBundle/Entity/User','csrf_protection' =>false));}publicfunctiongetName(){return'my_awesome_form';}}

Next, we’ll want to actually create our addUserAction():


/** * POST Route annotation. * @Rest/Post("/users/new.{_format}") * @Rest/View * @return array */public function addUserAction(Request $request){ $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->createUser(); $form = $this->createForm(new /ApiBundle/Form/Type/RegistrationFormType(), $user); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush(); return array('user' => $user); } return View::create($form, 400);} /** * POST Route annotation. * @Rest/Post("/users/new.{_format}") * @Rest/View * @return array */publicfunctionaddUserAction(Request$request){$userManager=$this->container->get('fos_user.user_manager');$user=$userManager->createUser();$form=$this->createForm(new/ApiBundle/Form/Type/RegistrationFormType(),$user);$form->handleRequest($request);if($form->isValid()){$em=$this->getDoctrine()->getManager();$em->persist($user);$em->flush();returnarray('user'=> $user);}returnView::create($form,400);}

To make a request, you’ll need to send the data as raw JSON,to our endpoint:

{ "my_awesome_form":{ "email":"[email protected]", "username":"sdsa", "plainPassword":"asd" }} { "my_awesome_form":{ "email":"[email protected]", "username":"sdsa", "plainPassword":"asd" }}

And that’s all there is to it.

We haven’t covered the cases where you’d want Delete or Update a user yet. Updating resources through the REST standards can be done using either PUT or PATCH. The difference between them is that PUTwill completely replace your resource, while PATCH will only, well, patch it… meaning that it will partially update your resource with the input it got from the API request.

Let’s get to it then. We’ll use the same form as before, and we’ll try to only change (we’ll use the PATCH verb for that) the email address, username and password of our previously created user:


/** * PATCH Route annotation. * @Rest/Patch("/users/edit/{id}.{_format}") * @Rest/View * @return array */public function editAction(Request $request, $id){ $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->findUserBy(array('id'=>$id)); $form = $this->createForm(new /ApiBundle/Form/Type/RegistrationFormType(), $user, array('method' => 'PATCH')); $form->handleRequest($request); if ($user) { if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush(); return array('user' => $user); } else { return View::create($form, 400); } } else { throw $this->createNotFoundException('User not found!'); }} /** * PATCH Route annotation. * @Rest/Patch("/users/edit/{id}.{_format}") * @Rest/View * @return array */publicfunctioneditAction(Request$request,$id){$userManager=$this->container->get('fos_user.user_manager');$user=$userManager->findUserBy(array('id'=>$id));$form=$this->createForm(new/ApiBundle/Form/Type/RegistrationFormType(),$user,array('method'=>'PATCH'));$form->handleRequest($request);if($user){if($form->isValid()){$em=$this->getDoctrine()->getManager();$em->persist($user);$em->flush();returnarray('user'=>$user);}else{returnView::create($form,400);}}else{throw$this->createNotFoundException('User not found!');}}

The request body is the same as the one shown for the POST method, above. There are a few small differences in our edit actionthough. First off – we’re telling our form to use the PATCH method. Second – we are handling the case where the user ID provided isn’t found.

The Delete method is the easiest one yet. All we need to do is to find the user and remove it from our database. If no user is found, we’ll throw a “user not found” error:


/** * DELETE Route annotation. * @Rest/Delete("/users/delete/{id}.{_format}") * @Rest/View(statusCode=204) * @return array */public function deleteAction($id){ $em = $this->getDoctrine()->getManager(); $user = $em->getRepository('AppBundle:User')->find($id); if ($user){ $em->remove($user); $em->flush(); } else { throw $this->createNotFoundException('User not found!'); }} /** * DELETE Route annotation. * @Rest/Delete("/users/delete/{id}.{_format}") * @Rest/View(statusCode=204) * @return array */publicfunctiondeleteAction($id){$em=$this->getDoctrine()->getManager();$user=$em->getRepository('AppBundle:User')->find($id);if($user){$em->remove($user);$em->flush();}else{throw$this->createNotFoundException('User not found!');}} Conclusions

Aaand we’re done. We now have a fully working CRUD for our User Entity. Thanks for reading and please do share your opinions/suggestions in the comment section below.