Dieses Blog durchsuchen

Samstag, 16. Juli 2016

symfony3: create a restful api controller

We want to implement a basic api controller and a client to test it.

create a controller in your bundle.
Save it to AppBundle/controllers/Api/UserController.php
<?php
/**
* Created by PhpStorm.
* User: root
* Date: 16.07.16
* Time: 15:34
*/
namespace AppBundle\Controller\Api;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class UserController extends Controller {
/**
* @Route("/api/user")
* @Method("POST")
*/
public function newAction()
{
return new Response('this is it');
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
edit you routing under app/config/routing.yml and add the app_api part

app_api:
resource: "@AppBundle/Controller/Api"
type: annotation
view raw gistfile1.txt hosted with ❤ by GitHub
At that point the api controller is available unter "localhost:8000/api/user"

But we wan to write a short testfile, to test our api with gusszle.

add guzzle to your composer composer 
cmd->require eightpoints/guzzle-bundle

This loads guzzle.

Create a file named test.php in your project root
<?php
require __DIR__ . '/vendor/autoload.php';
$client = new \GuzzleHttp\Client();
$response = $client->post('http://localhost:8000/api/user');
echo $response->getBody();
view raw gistfile1.txt hosted with ❤ by GitHub
open a terminal an hit the file:
php test.php

You will get your controller response directly.

Keine Kommentare:

Kommentar veröffentlichen