Buy

POST: Creation, Location Header and 201

POST: Creation, Location Header and 201

Once the POST endpoint works, the client will send programmer details to the server. In REST-speak, it will send a representation of a programmer, which can be done in a bunch of different ways. It’s invisible to us, but HTML forms do this by sending data in a format called application/x-www-form-urlencoded:

POST /api/programmers HTTP/1.1
Host: localhost:8000
Content-Type: application/x-www-form-urlencoded

nickname=Geek+Dev1&avatarNumber=5

PHP reads this and puts it into the $_POST array. That’s ok for the web, but in the API world, it’s ugly. Why not, have the client send us the representation in a beautiful bouquet of curly braces known as JSON:

POST /api/programmers HTTP/1.1
Host: localhost:8000
Content-Type: application/json

{
    "nickname": "Geek Dev1",
    "avatarNumber": 5
}

Creating a request like this with Guzzle is easy:

// testing.php
// ...

$nickname = 'ObjectOrienter'.rand(0, 999);
$data = array(
    'nickname' => $nickname,
    'avatarNumber' => 5,
    'tagLine' => 'a test dev!'
);

$request = $client->post('/api/programmers', null, json_encode($data));
$response = $request->send();

echo $response;
echo "\n\n";

The second null argument is the request headers to send. We’re not worried about headers yet, so we can just leave it blank.

Coding up the Endpoint

Back in the ProgrammerController class, let’s make this work by doing our favorite thing - coding! First, how do we get the JSON string passed in the request? In Silex, you do this by getting the Request object and calling getContent() on it. Let’s just return the data from the endpoint so we can see it:

// src/KnpU/CodeBattle/Controller/Api/ProgrammerController.php
// ...

public function newAction(Request $request)
{
    $data = $request->getContent();
    return $data;
}

Tip

Your framework will likely have a shortcut for getting the request content or body. But if it doesn’t, you can get it by using this strange bit of code:

$data = file_get_contents('php://input');

This is a special stream that reads the request body. For more details, see php.net: php://.

Try running our testing.php file again:

$ php testing.php

This time, we see the JSON string being echo’ed right back at us:

HTTP/1.1 200 OK
...
Content-Type: text/html; charset=UTF-8

{"nickname":"ObjectOrienter31","avatarNumber":5}

Creating the Programmer Resource Object

Awesome! I’ve already created a Programmer class, which has just a few properties on it. I also created simple classes for the other two resources - Project and Battle. We’ll use these later.

In newAction, we have the JSON string, so let’s decode it and use the data to create a new Programmer object that’s ready for battle. We’ll use each key that the client sends to populate a property on the object:

// src/KnpU/CodeBattle/Controller/Api/ProgrammerController.php
// ...

public function newAction(Request $request)
{
    $data = json_decode($request->getContent(), true);

    $programmer = new Programmer($data['nickname'], $data['avatarNumber']);
    $programmer->tagLine = $data['tagLine'];
    // ...
}

Note

Do not forget to add use KnpU\CodeBattle\Model\Programmer; namespace for the Programmer class at the beginning of the ProgrammerController.php.

My app also has a really simple ORM that lets us save these objects to the database. How you save things to your database will be different. The key point is that we have a Programmer class that models how we want our API to look, and that we can somehow save this:

// src/KnpU/CodeBattle/Controller/Api/ProgrammerController.php
// ...

public function newAction(Request $request)
{
    $data = json_decode($request->getContent(), true);

    $programmer = new Programmer($data['nickname'], $data['avatarNumber']);
    $programmer->tagLine = $data['tagLine'];
    $programmer->userId = $this->findUserByUsername('weaverryan')->id;

    $this->save($programmer);

    return 'It worked. Believe me - I\'m an API';
}

At the bottom, I’m just returning a really reassuring message that everything went ok.

Faking the Authenticated User

I’ve also added one really ugly detail:

$programmer->userId = $this->findUserByUsername('weaverryan')->id;

Every programmer is created and owned by one user. On the web, finding out who is creating the programmer is as easy as finding out which user is currently logged in.

But our API has no idea who we are - we’re just a client making requests without any identification.

We’ll fix this later. Right now, I’ll just make every programmer owned by me. Make sure to use my username: it’s setup as test data that’s always in our database. This test data is also known as fixtures.

Ok, the moment of truth! Run the testing script again:

$ php testing.php
HTTP/1.1 200 OK
Host: localhost:8000
...
Content-Type: text/html; charset=UTF-8

It worked. Believe me - I'm an API

The message tells us that it probably worked. And if you login as weaverryan with password foo on the web, you’ll see this fierce programmer-warrior in the list.

Status Code 201

But no time to celebrate! Our response is a little sad. First, since we’ve just created a resource, the HTTP elders say that we should return a 201 status code. In Silex, we just need to return a new Response object and set the status code as the second argument:

// src/KnpU/CodeBattle/Controller/Api/ProgrammerController.php
// ...

public function newAction(Request $request)
{
    // ...
    $this->save($programmer);

    return new Response('It worked. Believe me - I\'m an API', 201);
}

Running the testing script this time shows us a 201 status code.

Location Header

And when we use the 201 status code, there’s another rule: include a Location header that points to the new resource. Hmm, we don’t have an endpoint to get a single programmer representation yet. To avoid angering the RESTful elders, let’s add a location header, and just fake the URL for now:

// src/KnpU/CodeBattle/Controller/Api/ProgrammerController.php
// ...

public function newAction(Request $request)
{
    // ...
    $this->save($programmer);

    $response = new Response('It worked. Believe me - I\'m an API', 201);
    $response->headers->set('Location', '/some/programmer/url');

    return $response;
}

If you stop and think about it, this is how the web works. When we submit a form to create a programmer, the server returns a redirect that takes us to the page to view it. In an API, the status code is 201 instead of 301 or 302, but the server is trying to help show us the way in both cases.

Try the final product out in our test script:

$ php testing.php
HTTP/1.1 201 Created
...
Location: /some/programmer/url
Content-Type: text/html; charset=UTF-8

It worked. Believe me - I'm an API

Other than the random text we’re still returning, this endpoint is looking great. Now to GET a programmer!

Leave a comment!

  • 2016-10-06 weaverryan

    Hey Maksym!

    We have it because it's still relevant (the changes from Symfony 2 to 3 - other than the directory structure changes - are quite minor). We have a few other things on the Symfony 3 track that are done with later versions of Symfony 2, but are still relevant. And in this case, we *do* switch to Symfony 3 during Course 4 - so the series is a bit mixed!

    Cheers!

  • 2016-10-06 Maksym Minenko

    Why is this on the Symfony *3* track, I wonder?

  • 2016-09-07 Victor Bocharsky

    Hey Prakash,

    Everything is mostly the same. First of all you need to upgrade composer dependencies according to the Symfony 3. To do that, you should ensure that bundles you use in project support Symfony 3.x, check its composer.json file to see symfony/framework-bundle: ^2.0 || ^3.0. If you see "^3.0" - it should work and you can do upgrade.
    P.S. Don't forget to fix all deprecations in 2.8 before upgrading. We have a tutorial about it:
    How to Upgrade to Symfony 2.8, then 3.0
    .

    Cheers!

  • 2016-09-06 Prakash

    Hello how i do the REST API with syfmony 3.* version. currently example is with symfony 2.6. how i can migtae to syfmony 3?

  • 2016-08-23 weaverryan

    Hey Andjii!

    The tutorial uses guzzle/guzzle version 3.7, not guzzlehttp/guzzle at version 6 (which I'm guessing you are using). You can use the old, guzzle/guzzle just fine, or use the new library. But in that case, you'll need to do a little bit of translating for the new version of the library. Check out this comment for a few more details, including a gist with a version of testing.php that should work with the latest version :). http://knpuniversity.com/scree...

    But, to finally answer your question, you can't just echo the $response in Guzzle 6 (as you know), but you *can* print the body:

    echo $response->getBody();

    In some ways, the new version of the library is not as user-friendly as the old version. You can also check out this Response debugging function that we use in the Symfony REST tutorial: https://gist.github.com/weaver...

    Cheers!

  • 2016-08-23 Andjii

    Hello! I get the following error: Catchable fatal error: Object of class GuzzleHttp\Psr7\Response could not be converted to string in \testing.php on line 37. there is "echo $response". how should I convert my response object to string?

  • 2016-08-18 weaverryan

    Hey John!

    Yep - there are a few libraries that still work fine, but are older versions at this point. The only one that I know is actually *deprecated* is Guzzle. We use guzzle/guzzle at version 3, but the latest version os guzzlehttp/guzzle (yes it has a different name now) at version 6! We don't technically use this library for the API... but we do use it for *testing* the API. In the Symfony REST tutorial - starting on episode 4 (http://knpuniversity.com/scree... we use the latest and greatest version 6. So, if you're curious about the differences, you can compare. Otherwise, if you're here for the API stuff, I wouldn't worry about it :).

    About the 404 on the Font file, I'm not sure about that. If you download the starting code, there *is* a web/vendor/font-awesome/fonts/fontawesome-webfont.ttf file in the project - so it should be loading this just fine. It shouldn't affect anything either way (you might just be missing some cute icons) but the 404 is mysterious!

    Cheers!

  • 2016-08-17 John

    When I did a composer install, I did receive a ton of deprecation notices. But the app runs except in the browser console it says GET http://localhost:8000/vendor/font-awesome/fonts/fontawesome-webfont.ttf?v=4.0.3 404 (Not Found)

  • 2016-06-09 weaverryan

    Good find Vlad! That is a pretty subtle difference between the old and new version of Guzzle. Thanks for sharing!

  • 2016-06-08 Vlad

    Thanks Ryan! Changing base_url to base_uri fixed the issue for me. I'm using Guzzle 6.

  • 2016-05-18 weaverryan

    Nice catch!

  • 2016-05-18 weaverryan

    Hi Roberto!

    Actually, I would argue that testing.php is not better than Postman :). However, we will soon (in the next chapters in this tutorial) take the code from testing.php and turn them into true functional tests for our API. I believe this *is* better than Postman, because we now have a test suite that we can run at any time.

    Cheers!

  • 2016-05-16 Thierno Diop

    oki its good it was because in scurity.yml the A in api was writen in capital

  • 2016-05-16 Thierno Diop

    when i execute the testing.php file i am redirected to the login page is it normal ?

  • 2016-05-13 Roberto Briones Argüelles

    Why is better option to use the `testing.php` file instead Postman? Seems dirty to me.

  • 2016-03-24 cool

    im sorry but i have to say this, her voice is too sweet for the tutorial. it almost put me to sleep

  • 2016-03-16 weaverryan

    Hi Scott!

    Because you're using Symfony, if you use the built-in web server command from Symfony (php app/console server:run) it will start a built-in web server where it *defaults* to using app_dev.php - without you needing to have it in the URL. Alternatively, you can setup any other web server locally to have the same behavior.

    BUT, more generally, we do talk about this in our Symfony REST tutorial. In our tests, we use a hook into Guzzle that automatically prepends the URL: http://knpuniversity.com/scree.... In episode 4 (which I'm recording right now), I've updated the code that hooks into Guzzle to work for Guzzle version 6: http://knpuniversity.com/scree...

    I hope that helps - good question!

  • 2016-03-15 Scott Gutman

    In my testing.php i had to make the line $response = $client->post('/app_dev.php/api/programmers'); How do I change that?

  • 2016-01-17 Shairyar Baig

    Hi, I ended up using the version mentioned in tutorial tip and that fixed the problem.

  • 2016-01-16 weaverryan

    Hey Shairyar!

    Ah, the infamous "malformed URL" error - I get this a lot in my day-to-day work. Usually, it's because I've misconfigured the "base_uri" setting - so that when I request "/api/programmers", it literally tries to request this URI, instead of http://localhost:8000/api/programmers. Double check how you're setting the base_uri for whatever Guzzle version you're on. In Guzzle 5, I think the setting was base_url, and in 6, it's base_uri. Guzzle has been a tricky library lately, as many things have changed quickly.

    Cheers!

  • 2016-01-14 Shairyar Baig

    I am stuck at the same problem and the updated testing.php does not work either, if it helps this is the full error I am getting


    PHP Fatal error: Uncaught exception 'GuzzleHttp\Ring\Exception\RingException' with message 'cURL error 3: <url> malformed' in /Users/shairyar/Sites/REST/vendor/guzzlehttp/ringphp/src/Client/CurlFactory.php:127
    Stack trace:
    #0 /Users/shairyar/Sites/REST/vendor/guzzlehttp/ringphp/src/Client/CurlFactory.php(91): GuzzleHttp\Ring\Client\CurlFactory::createErrorResponse(Array, Array, Array)
    #1 /Users/shairyar/Sites/REST/vendor/guzzlehttp/ringphp/src/Client/CurlHandler.php(96): GuzzleHttp\Ring\Client\CurlFactory::createResponse(Array, Array, Array, Array, Resource id #78)
    #2 /Users/shairyar/Sites/REST/vendor/guzzlehttp/ringphp/src/Client/CurlHandler.php(68): GuzzleHttp\Ring\Client\CurlHandler->_invokeAsArray(Array)
    #3 /Users/shairyar/Sites/REST/vendor/guzzlehttp/ringphp/src/Client/Middleware.php(54): GuzzleHttp\Ring\Client\CurlHandler->__invoke(Array)
    #4 /Users/shairyar/Sites/REST/vendor/guzzlehttp/ringphp/src/Client/Middleware.php(30): GuzzleHttp\Ring\Client\Middleware::GuzzleHttp\Ring\Client\{closure}(Array)
    #5 /Users/shairyar/Sit in /Users/shairyar/Sites/REST/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 51

    Fatal error: Uncaught exception 'GuzzleHttp\Ring\Exception\RingException' with message 'cURL error 3: <url> malformed' in /Users/shairyar/Sites/REST/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 51

    GuzzleHttp\Exception\RequestException: cURL error 3: <url> malformed in /Users/shairyar/Sites/REST/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 51

    Call Stack:
    0.0001 225136 1. {main}() /Users/shairyar/Sites/REST/testing.php:0
    0.0071 1314064 2. GuzzleHttp\Client->post() /Users/shairyar/Sites/REST/testing.php:21
    0.0092 1683720 3. GuzzleHttp\Client->send() /Users/shairyar/Sites/REST/vendor/guzzlehttp/guzzle/src/Client.php:150

  • 2015-11-17 Noah Glaser

    I did the http_errors is false and it worked for me. Thank you
    'http_errors' => false

  • 2015-10-09 weaverryan

    Yo Azeem!

    I think you may be using a newer version of Guzzle than I am in the tutorial - I'm using 3.7 (which is quite old at this time). If you use something newer, you'll just need to translate a bit of the code. The full testing.php for the newest version of Guzzle would look something like this: https://gist.github.com/weaver.... Warning - I just hacked that together, it's probably not 100% perfect :).

    Or, you can use the 3.7 version - definitely the way to go if you just want to code through and learn the REST stuff.

    Cheers!

  • 2015-10-08 Azeem

    getting this error when I run testing.php

    Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 3: <url> malformed (see http://curl.haxx.se/libcurl/c/... in /Users/amichael/Public/www/justlikeme/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:187