computer
Articles » Creating a simple RESTful API endpoint in Silverstripe

Creating a simple RESTful API endpoint in Silverstripe

18 April, 2020

In this guide we’ll create a simple RESTful API endpoint that returns a list of items modelled on a very basic DataObject. We’ll create this endpoint by doing the following:

  1. Creating a controller with a method to handle requests to the endpoint.
  2. Whitelisting the controller method.
  3. Configuring a route for the endpoint with a routes.yml file.
  4. Testing our new endpoint.

Let’s say we have the following DataObject called Book and we want to retrieve a collection of books through an endpoint called ‘/api/books’.

class Book extends DataObject {

    private static $table_name = "Book";

    private static $db = [
        'Title' => 'Varchar',
        'Author' => 'Varchar',
        'Price' => 'Varchar'
    ];

}

 

Creating our controller and method to handle requests

Let’s create a controller called BooksApiController with a method called 'index' to expose the API and 'books' that will return all books when called.

class BooksApiController extends Controller {
    public function index(HTTPRequest $request) {
        return 'Books API';
    }

    public function books(HTTPRequest $request) {
        $books = Book::get();
        $booksList = [];
        
        foreach ($books as $book) {
            array_push($booksList, [
                'ID' => $book->ID,
                'Title' => $book->Title,
                'Author' => $book->Author,
                'Price' => $book->Price
            ]);
        }
    }
}

Now let’s also format our $booksList by encoding it as a json response and add some http headers

public function books(HTTPRequest $request) {
    
    // …

    $booksList = json_encode($booksList);

    $this->getResponse()->setBody($booksList);    
    $this->getResponse()->addHeader("Content-type", "application/json");
    $this->getResponse()->addHeader('Access-Control-Allow-Origin',
        "*"
    );    
    $this->getResponse()->addHeader("Access-Control-Allow-Methods", "GET");  
    $this->getResponse()->addHeader("Access-Control-Allow-Headers", "x-requested- 
    with");

    return $this->getResponse();
}

 

Whitelisting controller methods

Next let’s whitelist these two methods so they can be invoked via the URL by adding them both to the $allowed_actions array in the BooksApiController class. After whitelisting the methods, also flush the cache by appending ‘?flush=all’ to the site URL.

private static $allowed_actions = [
    'index',
    'books'
];

 

Configuring a route with a route.yml file

Create a route.yml file under the ‘app/_config/’ directory similar to the following and also flush the cache afterwards by appending '?flush=all' to your site URL.

---
Name: approutes
After: framework/_config/routes#coreroutes
---
SilverStripe\Control\Director:
  rules:
    'api//$Action/$ID/$Name': 'BooksApiController'

 

Testing the new endpoint

We’re now ready to test the endpoint. If you now go to ‘localhost/api/books’ you should get a similar response to the one below given you've already created records of the Book DataObject.

Post your comment

Comments

  • EPJ DEV
    7 November, 2022

    Gravatar for EPJ DEV

    nice

RSS feed for comments on this page | RSS feed for all comments