-
Notifications
You must be signed in to change notification settings - Fork 5
route
Aeria was born to make developers' life simple. You may sometimes need to expose some APIs to interact with your frontend: Aeria's here to help.
Let's get back to our book example: we now want to expose an API to fetch all the saved book titles.
First, in our functions.php
we've got to declare a Controller extending \Aeria\Router\Controller
, let's call it BooksController. Inside it, we need a method that fetches all our books, and returns them in json format.
Make sure Aeria is installed and active by checking if function_exists('aeria')
.
Finally, we register our controller in Aeria. An alternative to this type of controller registration is declaring a new Controller config file.
if (function_exists('aeria')) {
class BooksController extends \Aeria\Router\Controller
{
public function fetchBooks()
{
$books = get_posts(
[
"post_type" => "book"
]
);
return $books;
}
}
$controller_register = aeria('controller');
$controller_register->register(BooksController::class);
}
###Declaring the route in the configuration
Now that we've created our controller, we just need to declare a configuration file for our route. Like every other configuration file, we need to set the 3 main fields:
-
"name"
defines the name for this route. -
"kind"
defines the type of configuration: we're gonna set it to "route" this time. -
"spec"
defines the specific configurations for the object.
{
"name": "books_route",
"spec": {},
"kind": "route"
}
If you want to leave this configuration disabled for now, you can add "enabled": false
to these fields.
Now, we need to declare the route's specs. Routes need 3 fields:
-
"path"
sets the URL where we want to expose the API. Please note that the path you set will be concatenated tohttp://example.com/wp-json/aeria[your path]
. We'll set it to"/fetch-books"
-
"method"
sets the HTTP request method to use. Right now, you can use- POST
- GET
- PUT
- DELETE
-
"handler"
is your function's callable. We're gonna set it to"BooksController@fetchBooks"
Our config file now looks like this:
{
"name": "books_route",
"spec": [
{
"path":"/fetch-books",
"method":"GET",
"handler":"BooksController@fetchBooks"
}
],
"kind": "route"
}
You can now try to call your API.