Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
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

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

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!

6
Login or Register to join the conversation
Default user avatar
Default user avatar Zuhayer Tahir | posted 5 years ago

in showAction($nickname), when I try to get a programmer from the repository, PhpStorm does not auto Complete finOneByNickName(). It only shows the 4 default methods. I am working with the project files and the function is present in ProgrammerRepository.

/**
* @Route("/api/programmers/{nickname}")
* @Method("GET")
*/
public function showAction($nickname)
{
$programmer = $this->getDoctrine()
->getRepository('AppBundle:Programmer')->findOneBy(array(''))
->find__________
;

$data = array(
'nickname' => $programmer->getNickName(),
'avatarNumber' => $programmer->getAvatarNumber(),
'powerLevel' => $programmer->getPowerLevel(),
'tagLine' => $programmer->getTagLine(),
);

return new Response(json_encode($data));
}
Any suggestions on where i am going wrong?

---------------------------------------------
P.s. previously output works fine.
/d/wamp/www/symfony-rest $ php testing.php
HTTP/1.1 200 OK
Host: localhost:8000
Connection: close
X-Powered-By: PHP/5.5.12
Cache-Control: no-cache
Date: Fri, 02 Dec 2016 08:06:02 GMT
Content-Type: text/html; charset=UTF-8
X-Debug-Token: b8529d
X-Debug-Token-Link: /_profiler/b8529d

Hi ObjectOrienter699

Reply

Hey Zuhayer,

I suppose you have already installed and enabled Symfony plugin for PhpStorm, right?
I see an error in your code, you need to call findOneByNickName() right after getRepository(), i.e. get rid of findOneBy(array('')) method in your call chain. The correct code is:


$programmer = $this->getDoctrine()
    ->getRepository('AppBundle:Programmer')
    ->findOneByNickName($nickname)
;

Does it help you?

Cheers!

Reply
Default user avatar
Default user avatar Zuhayer Tahir | Victor | posted 5 years ago

I had installed the PhpStorm plugin, but forgot to Enable it. Thanks a bunch for the help.

Error in code was copy/paste error on my part.

Reply

Great! I'm glad it works now ;)

Cheers!

1 Reply
Default user avatar
Default user avatar karolos | posted 5 years ago

Hi , I have a problem starting with this course.
I downloaded the course from chapter 4 but I can't make it run .

When I run `php testing.php` I get the following error:

`Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 3: <url> malformed (see http://curl.haxx.se/libcurl... in C:\..\..\..\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.
php:187
Stack trace:
#0 C:\..\..\..\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(150): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
#1 C:\..\..\..\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(103): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleH
ttp\Handler\CurlFactory))
#2 C:\..\..\..\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Ha
ndler\CurlFactory))
#3 C:\..\..\..\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(28): GuzzleHttp\Handle in C:\..\..\..\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 187`

Reply

Hey Karolos
That error means that something in the URL was not properly formatted
Can you show me how your testing.php file looks like ?

Have a nice day!

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

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
    }
}
userVoice