Web Service REST

New topics about Symfony 2 should go here

Moderators: dcobalt, tiagojsag

Web Service REST

Postby infophp » Wed Mar 28, 2012 1:39 pm

Hi all

I want to implement a web service with Symfony 2 using REST and Json, but i diden't find doccumentation about that
please can anyone help me to do that.

thx for all
infophp
Junior Member
 
Posts: 8
Joined: Wed Mar 28, 2012 1:35 pm

Re: Web Service REST

Postby blogsh » Wed Mar 28, 2012 2:18 pm

Where are you stuck exactly?

You can define a requirement on the method of a request in your routes:
Code: Select all
    /**
     * @Route("/rest", requirements={"_method" = "GET"})
     */
    public function getAction()
    {
        return new Response('<form method="post" action="/rest"><input type="submit" value="Click" /></form>');
    }

    /**
     * @Route("/rest", requirements={"_method" = "POST"})
     */
    public function postAction()
    {
        return new Response('POST');
    }


And you can return json data either if you use the default PHP methods for json and set the content-type of your response:
Code: Select all
$response = new Response(json_encode($myArray));
$response->headers->set('Content-Type', 'application/json');


It's also possible to define the response format in the route so you can omit the last line:
Code: Select all
    /**
     * @Route("/rest", requirements={"_method" = "GET"}, defaults={"_format" = "json"})
     */
    public function showAction()
    {
        $data = /* ... */;
        return new Response(json_encode($data));
    }


A all-in-one alternative seems to be FOSRestBundle: https://github.com/FriendsOfSymfony/FOSRestBundle
blogsh
Faithful Member
 
Posts: 501
Joined: Thu Mar 03, 2011 9:35 pm
Location: Germany

Re: Web Service REST

Postby infophp » Wed Mar 28, 2012 2:52 pm

thx you so much for your help it helps me a lot.
infophp
Junior Member
 
Posts: 8
Joined: Wed Mar 28, 2012 1:35 pm

Re: Web Service REST

Postby bass_rock » Wed Apr 04, 2012 8:13 am

How can you use the FOSRestBundle with FOSUserManager so that the user has to login first, and you can make requests with the specified user?
bass_rock
Junior Member
 
Posts: 16
Joined: Fri Oct 28, 2011 8:27 am


Return to General Symfony 2 discussion

Who is online

Users browsing this forum: No registered users and 2 guests