eyja/rest-bundle

There is no license information available for the latest version (dev-master) of this package.

Framework for creating REST APIs using Doctrine entities

dev-master 2014-05-09 09:43 UTC

This package is not auto-updated.

Last update: 2024-11-04 14:35:55 UTC


README

Work in progress

TLDR; RESTful API autogenerated from Symfony+Doctrine entities. Go to docs to see how it looks like.

Setup

To get started, install this bundle in your Symfony project, and register it in AppKernel.

composer require eyja/rest-bundle dev-master

# /app/AppKernel.php
new Eyja\RestBundle\EyjaRestBundle()

Minimal example

Create new bundle for Your REST API:

php app/console generate:bundle \
    --no-interaction --namespace=Acme/RestBundle --dir=src --format=yml

Change autogenerated routing definition for new bundle to look something like this:

# app/config/routing.yml
acme_rest:
    prefix: /api/v1/
    resource: @AcmeRestBundle/Resources/config/routing.yml
    type: rest

Create new doctrine entitiy:

php app/console generate:doctrine:entity \
    --no-interaction --entity=AcmeRestBundle:Cat \
    --fields="name:string(100)" --format=yml
php app/console doctrine:schema:update --force

Define serialization for this entity:

# src/Acme/RestBundle/Resources/serializer/Entity.Cat.yml
Acme\RestBundle\Entity\Cat:
    properties:
        id:
            type: integer
            groups: [collection, single]
        name:
            type: string
            groups: [collection, single]

Create simplest controller ever, no class required just service:

# src/Acme/RestBundle/Resources/config/services.yml
services:
  acme_rest.controller.cat:
    parent: eyja_rest.abstract_controller
    arguments: [AcmeRestBundle:Cat, cat]
    tags: [ { name: rest.controller } ]

Viola! You can use your new api:

php app/console router:debug
rest_cat_getSingle                GET    ANY    ANY  /api/v1/cat/{id}
rest_cat_getCollection            GET    ANY    ANY  /api/v1/cat
rest_cat_create                   POST   ANY    ANY  /api/v1/cat
rest_cat_update                   PUT    ANY    ANY  /api/v1/cat/{id}
rest_cat_delete                   DELETE ANY    ANY  /api/v1/cat/{id}

curl -XPOST http://localhost/app_dev.php/cat -HContent-Type:\ application/json \
    -d'{"name":"Lucifer"}'
{"id":1,"name":"Lucifer"}

curl -XGET http://localhost/app_dev.php/cat/1
{"id":1,"name":"Lucifer"}

curl -XPUT http://localhost/app_dev.php/cat/1 -HContent-Type:\ application/json \
    -d'{"name":"Lucifer -.-"}'
{"id":1,"name":"Lucifer -.-"}

curl -XGET http://localhost/app_dev.php/cat
{"results":[{"id":1,"name":"Lucifer"}],"_metadata":{"limit":20,"offset":0,"total":1}}

curl -XDELETE http://localhost/app_dev.php/cat/1
# Empty response, http status code 204

Larger example

To see more complex example see demo bundle, featuring custom routes and advanced serialization.

Documentation

  1. Generated API.
  2. Creating rest controller.