JSON APIs with Laravel: Part 1 - Learning the Ropes
Oliver Sarfas • July 8, 2019programming laravel
Most of a server-side / back-end developer's role will involve integrating with, or serving up APIs. In this short series, we're going to make our own very basic JSON API using Laravel. I'm not sure how long the series will be, however I'd like to cover the following points;
- Why JSON?
- What is CRUD / BREAD?
- Creating our data using Laravel Models & Eloquent
- Exposing our Models on the Web
- Validating incoming requests for creating, updating, and deleting model(s)
- Testing the API
- Future concerns
So let's get started with the first two points shall we
A lot of online guides (the older ones especially) will use XML and SOAP API services. Over the last 8 or so years, especially in the last 5 - XML has gradually been phased out in favour of JSON. But why?
JSON is easier to read
XML whilst highly structured and hierarchical, is a nightmare to read as a human compared to JSON. It's not impossible, nor terrible, just nowhere near as clean and simplistic.
XML is slower
This can depend on your software. C# for instance is very good at converting to XML. Others however, not so much. Consuming XML can be a resource-intensive procedure due to all the complexities that XML can offer in it's atttributes.
JSON is restrictive
Sounds bad right? Where XML is a tree structure, JSON is a map (key-value-pair mapping).
This can be limiting to data, however it's a good thing as it makes data predictable, and easy to understand
What is CRUD / BREAD?
Speak to any developer and they'll know what CRUD is. It's our "bread and butter". We do this everyday in some remit.
CRUD is an acronym for Create, Read, Update, Delete. The four core functions that allow for management of a "resource".
BREAD is a relatively new term that I found a couple of years ago and have been using instead of CRUD. In most modern web applications, you generally have an index of the resource. For instance;
We have users that we would like to manage. You'd expect there to be the following functionality;
- List all users
- Add a new user
- Look at that user / any given user
- Update a user
- Delete a user
5 points, not the initial 4 that CRUD would lead us to build. That's where BREAD comes in. Browse, Read, Edit, Add, Delete.
The 5 points listed above match BREAD perfectly.
Luckily enough, Laravel's
artisan make:controller UserController -r will make a resource controller, which scaffolds out all this functionality for us!
In the next part of the series we'll actually get into some code!
We're going to be creating our Model(s) using Laravel, ensuring that they have data using Factories and Seeders before moving onto exposing them via an API endpoint on the web!