-
Notifications
You must be signed in to change notification settings - Fork 6
Extending the APIs
With the implementation of the Command pattern, adding an API is as easy as writing a class file and registering it as a service. Let us go through the steps of adding an API using an example illustrated below:
Important: In all your written code, you are expected to follow the PSR-2 coding standard and the Symfony coding standard.
-
Choose a name for the new API. In this example, we will create an API named
MyNewApi
. -
Create a class file in the directory
Symfony/src/Codebender/LibraryBundle/Handler/ApiCommand/
that implements theAbstractApiCommand
class. In this example, we will create a class file namedMyNewApiCommand.php
with the following contents:<?php namespace Codebender\LibraryBundle\Handler\ApiCommand; use Doctrine\ORM\EntityManager; use Symfony\Component\DependencyInjection\ContainerInterface; class MyNewApiCommand extends AbstractApiCommand { public function execute($content) { // perform input validation here if ($content === null) { return ['success' => false, 'message' => 'Invalid input']; } // perform the actual execution of the API here return ['success' => true, 'message' => 'Yay!']; } }
-
Register the new command as a service in
Symfony/src/Codebender/LibraryBundle/Resources/config/services.yml
. In this example, we will add the following lines toservices.yml
:.... <some other registered API classes> .... codebender_api.myNewApi.class: Codebender\LibraryBundle\Handler\ApiCommand\MyNewApiCommand` .... <some other registered API services> .... codebender_api.myNewApi: class: %codebender_api.myNewApi.class% arguments: entityManager: "@doctrine.orm.entity_manager" containerInterface: "@service_container"
-
That's pretty much it to get your API working. You may now access your API by sending a POST request to
/{authorization_key}/v2
with a request body of{"type":"myNewApi"}
. However, here at Eratosthenes, we would like to encourage good software engineering practices and that includes writing tests and documentation for your new API. So let's add a test in the fileSymfony/src/Codebender/LibraryBundle/Tests/Controller/ApiControllerTest.php
for our new API:public function testMyNewApiCommand() { $this->assertTrue(true); }
-
Hurray! We've now added a test that would always pass (note that this is only for illustration - in reality, a test that would pass regardless of anything else is obviously redundant). As a final step, let's add some documentation for our API in the API wiki page. As a general guideline, you are encouraged to write a brief description of your new API, the request body for calling your API and an example that will illustrate how your API is used.
-
Congratulations! You're now done with adding a new API!