Symfony – Create Rest server

Notes

We will assume that ApiBundle have been generated with:

# php app/console generate:bundle --namespace=Acme/ApiBundle --format=yml

and the routing to ApiBundle is:

// app/config/routing.yml
acme_api:
    resource: "@AcmeApiBundle/Resources/config/routing.yml"
    prefix:   /api

Composer install

Use –no-update option to gain some time during installation. composer update will only update everything at the end.

composer require "friendsofsymfony/rest-bundle" --no-update
composer require "jms/serializer-bundle" --no-update
composer update

Kernel config

// app/AppKernel.php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            /.../
            new FOS\RestBundle\FOSRestBundle(),
            new JMS\SerializerBundle\JMSSerializerBundle(),
            /.../

Routing config

Add the bundle route

// src/ApiBundle/Resources/config/routing.yml
   
acme_api_rest:
    prefix: /rest
    type: rest
    resource: "Acme\ApiBundle\Controller\RestController"

Controller config

headers

If you make calls on the same server, add these headers:

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

for Get actions

In this example, the route is directly set in the header of the function

// src/ApiBundle/Controller/RestController.php
    
namespace Acme\ApiBundle\Controller;
    
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
    
class RestController extends FOSRestController
{
    /**
     * @Route("/echo/{var}")
     */
    public function getEchoAction($var)
    {
        return New JsonResponse(array('Hello ' => $var));
    }
    /.../

for Post actions

namespace Acme\ApiBundle\Controller;
    
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
       
class RestController extends FOSRestController
{
    /.../
    /**
     * @Route("/submit")
     */
    public function postSubmitAction(Request $request)
    {
        if (0 === strpos($request->headers->get('Content-Type'), 'application/json'))
        {
            $res = $request->getContent();
            $data = json_decode($res);
            return New JsonResponse($data);
        }
        else
        {
            return New JsonResponse(array("error" => "JSON syntax require"));
        }
    }

for Post actions

For access control problem, add just after namespace:

header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS ');
header('Allow GET, POST, PUT, DELETE, OPTIONS ');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, *');

Test Rest server

call with Get

Execute:

# curl -i localhost/api/rest/echo/test

This should return

{"Hello":"test"}

call with Post

Execute:

#  curl -X POST -H "Content-Type: application/json" -d '{"test":"t"}' localhost/api/rest/submit

Raphaël has written 45 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>