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.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login SubscribeCreating 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:
// ... 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.
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