This bundle provide fast and simple way to generate REST api for your project entities without editing configs and creating any controllers.
- CRUD web api
- Independent from other bundles and do not required bundles like FOSRestBundle or JMSSerializerBundle, etc..
- Built-in pagination and ordering
- Download via composer
$ composer require jmd/rest-bundle
- Add into
app/AppKernel.php
:
public function registerBundles()
{
$bundles = array(
...
new JMD\RestBundle\JMDRestBundle(),
...
);
...
return $bundles;
}
- Add into
app/config/routing.yml
:
jmd_rest:
resource: "@JMDRestBundle/Controller/RestController.php"
type: annotation
prefix: /api
Update, delete and add methods you can use as is after installation.
bundleName
- name of entity bundleentityName
- name of entityid
- entity item id
name | method | path | comment |
---|---|---|---|
rest_get_entity_list | GET | /api/{bundleName}/{entityName} | Show list entity items |
rest_get_entity_item | GET | /api/{bundleName}/{entityName}/{id} | Show entity item by id |
rest_update_entity_item | PUT | /api/{bundleName}/{entityName}/{id} | Update entity item by id |
rest_x_update_entity_item | PUT | /api/{bundleName}/{entityName}/{id}/x | Special update action for x-editable jQuery plugin |
rest_delete_entity_item | DELETE | /api/{bundleName}/{entityName}/{id} | Delete entity item id |
rest_entity_add_item | POST | /api/{bundleName}/{entityName} | Add new entity item |
Request headers must have Content-Type
equals application/json
.
For update any field in entity we must construct there json structure:
{
"fieldName": "value",
"fieldName2": "value"
}
Updating and posting supports relations. To save relations we have to set json like:
{
"relationFieldToMany": [id1,id2],
"relationFieldToOne": id3
}
For showing item in entity repository we must implement \JMD\RestBundle\Entity\RestEntityInterface
and make methods:
findAllArray(array $order = [])
- must return query builder. Example:
public function findAllArray(array $order = [])
{
$qb = $this->createQueryBuilder('c');
$qb->select('partial c.{id,name}');
return $qb;
}
findOneArray($id)
- must return array or null result. Example:
public function findOneArray($id)
{
$qb = $this->createQueryBuilder('c');
$qb
->select('partial c.{id,name}')
->where('c.id = :id')
->setParameter('id', $id)
;
return $qb->getQuery()->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY);
}
After you make implementation, you can send GET request and will get result like this:
# url: http://localhost/api/BundleName/Client
{
"status": 200,
"data": [
{
"id": 1,
"name": "Test client"
},
{
"id": 2,
"name": "Test client 2"
}
]
}
# url: http://localhost/api/BundleName/Client/1
{
"status": 200,
"data": {
"id": 1,
"name": "Test client"
}
}
That's all!