Documentation driven API Development using Laravel, Dredd and Apiary
Apiary, Dredd & Laravel
Currently at Frianbiz we tried a new approach “driven by doc”. Small demo with an “from scratch” PHP Laravel API:
We begin our API by documentation with apiary.io
apiary.io is used to write documentation on BluePrint format with live preview of generated doc.
Our “Blog” API has only 2 services: GET /article et POST /article
FORMAT: 1A
# blog
Blog is a simple API allowing consumers...
## Article Collection [/article]
### List All Articles [GET]
+ Response 200 (application/json)
[
{
"title": "Article 1",
"content": "content"
},
{
"title": "Article 2",
"content": "content"
}
]
### Create a New Article [POST]
You may create your own article using this action. It takes a JSON
object containing...
+ Request (application/json)
{
"title": "My new post",
"content": "new article content",
}
+ Response 201 (application/json)
+ Body
{
"status":"created"
}
Creating our API “blog” with Laravel
composer create-project — prefer-dist laravel/laravel blog
Our goal is to compare our API and its doc with Dredd
After installing Dredd in our Laravel project (detail here) we launched Dredd in command line on the project root:
https://jsapi.apiary.io/apis/blog41.apib is documentation url
http://blog.dev is API url
dredd https://jsapi.apiary.io/apis/blog41.apib http://blog.dev
Obviously at this point, no service was implemented …
We quickly made our services code with Laravel,
php artisan make:controller ArticleController
We create our Route::resource(‘article’, ‘ArticleController’) and associated controller
class ArticleController extends Controller
{
public function index(Request $request)
{
$collection = array([“title” => “title 1”, “content” => “content 1”], [“title” => “title 2”, “content” => “content 2”]);
return response()->json($collection);
}public function store(Request $request)
{
return response()->json([“status” => “success”], 201);
}}
we launch dredd again
dredd https://jsapi.apiary.io/apis/blog41.apib http://blog.dev
Success!
Bonus, you can link Dredd and apiary for more readable reports. For example by removing the key “title” in json returned by GET /article in my Laravel application, it looks like this
Project source: https://github.com/vincentlg/Demo-API-with-Laravel-drive-by-Apiaray-test-by-Dredd
Documentation: http://docs.blog41.apiary.io/