This tutorial has a new version, check it out!

GET one Programmer

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $10.00

Creating a programmer check! Next let's add the endpoint to return a single programmer. Add a public function showAction(). And even though it technically could be anything we dream up, the URL for this will follow a predictable pattern: /api/programmers/ and then some identifier. This might be an {id}, but for us each programmer has a unique nickname, so we'll use that instead. Don't forget the @Method("GET"):

... lines 1 - 38
/**
* @Route("/api/programmers/{nickname}")
* @Method("GET")
*/
public function showAction($nickname)
{
... line 45
}
... lines 47 - 48

A client will use this to GET this programmer resource.

Add the $nickname argument and kick things off just by returning a new Response that says hi to our programmer:

... lines 1 - 38
/**
* @Route("/api/programmers/{nickname}")
* @Method("GET")
*/
public function showAction($nickname)
{
return new Response('Hello '.$nickname);
}
... lines 47 - 48

Testing this Endpoint

Every time we create a new endpoint, we're going to add a new test. Ok, we don't really have tests yet, but we will soon! Right now, go back to testing.php and make a second request. The first is a POST to create the programmer, and the second is a GET to fetch that programmer.

Change the method to get() and the URI will be /api/programmers/ plus the random $nickname variable. And we don't need to send any request body:

29 lines testing.php
... lines 1 - 11
$nickname = 'ObjectOrienter'.rand(0, 999);
... lines 13 - 17
// 1) Create a programmer resource
$response = $client->post('/api/programmers', [
'body' => json_encode($data)
]);
// 2) GET a programmer resource
$response = $client->get('/api/programmers/'.$nickname);
echo $response;
echo "\n\n";

Alright, let's try it!

php testing.php

Well Hello ObjectOrienter564 and Hello also ObjectOrienter227. Nice to meet both of you.

Returning the Programmer in JSON

Instead of saying Hello, it would probably be more helpful if we sent the Programmer back in JSON. So let's get to work. First, we need to query for the Programmer: $this->getDoctrine()->getRepository('AppBundle:Programer') and I already have a custom method in there called findOneByNickname():

... lines 1 - 38
/**
* @Route("/api/programmers/{nickname}")
* @Method("GET")
*/
public function showAction($nickname)
{
$programmer = $this->getDoctrine()
->getRepository('AppBundle:Programmer')
... lines 47 - 56
}
... lines 58 - 59

Don't worry about 404'ing on a bad nickname yet. To turn the entity object into JSON, we'll eventually use a tool called a serializer. But for now, keep it simple: create an array and manually populate it: a nickname key set to $programmer->getNickname() and avatarNumber => $programmer->getAvatarNumber(). Also set a powerLevel key - that's the energy you get or lose when powering up - and finish with the tagLine:

... lines 1 - 44
$programmer = $this->getDoctrine()
->getRepository('AppBundle:Programmer')
->findOneByNickname($nickname);
$data = array(
'nickname' => $programmer->getNickname(),
'avatarNumber' => $programmer->getAvatarNumber(),
'powerLevel' => $programmer->getPowerLevel(),
'tagLine' => $programmer->getTagLine(),
);
... lines 55 - 59

Return whatever fields you want to: it's your API, but consistency is king.

Now all we need to do is json_encode that and give it to the Response:

... lines 1 - 41
public function showAction($nickname)
{
... lines 44 - 47
$data = array(
'nickname' => $programmer->getNickname(),
'avatarNumber' => $programmer->getAvatarNumber(),
'powerLevel' => $programmer->getPowerLevel(),
'tagLine' => $programmer->getTagLine(),
);
return new Response(json_encode($data), 200);
}
... lines 57 - 58

Our tools will get more sophisticated and fun than this. But keep this simple controller in mind: if things get tough, you can always back up to creating an array manually and json_encoding the results.

Let's try the whole thing:

php testing.php

Hey, nice JSON.

Leave a comment!

This tutorial uses an older version of Symfony. The concepts of REST are still valid, but I recommend using API Platform in new Symfony apps.

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "2.6.*", // v2.6.11
        "doctrine/orm": "~2.2,>=2.2.3,<2.5", // v2.4.7
        "doctrine/dbal": "<2.5", // v2.4.4
        "doctrine/doctrine-bundle": "~1.2", // v1.4.0
        "twig/extensions": "~1.0", // v1.2.0
        "symfony/assetic-bundle": "~2.3", // v2.6.1
        "symfony/swiftmailer-bundle": "~2.3", // v2.3.8
        "symfony/monolog-bundle": "~2.4", // v2.7.1
        "sensio/distribution-bundle": "~3.0,>=3.0.12", // v3.0.21
        "sensio/framework-extra-bundle": "~3.0,>=3.0.2", // v3.0.7
        "incenteev/composer-parameter-handler": "~2.0", // v2.1.0
        "hautelook/alice-bundle": "0.2.*", // 0.2
        "jms/serializer-bundle": "0.13.*" // 0.13.0
    },
    "require-dev": {
        "sensio/generator-bundle": "~2.3", // v2.5.3
        "behat/behat": "~3.0", // v3.0.15
        "behat/mink-extension": "~2.0.1", // v2.0.1
        "behat/mink-goutte-driver": "~1.1.0", // v1.1.0
        "behat/mink-selenium2-driver": "~1.2.0", // v1.2.0
        "phpunit/phpunit": "~4.6.0" // 4.6.4
    }
}