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:
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'
];
}
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();
}
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'
];
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'
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
nice
No one has commented on this page yet.
RSS feed for comments on this page | RSS feed for all comments