REST API Best Practices & Implementing in Codeigniter
The document outlines the significance of REST APIs in product development and provides a comprehensive guide on implementing REST APIs using CodeIgniter. It includes best practices, HTTP verb usage, resource identification, error handling, and project structuring. The author emphasizes creating developer-friendly APIs and offers examples for common operations and routing implementation.
Introduction to REST API and its significance in product development, with a focus on implementing REST in CodeIgniter.
Emphasizes 'Single Source of Truth' and the importance of developer experience, treating developers as API customers.
Lists essential practices such as defining endpoints, using HTTP verbs, mapping relationships, and implementation techniques for optimal user experience.
Guidelines on error messaging with standardized responses and the importance of implementing robust authentication and documentation.
Step-by-step guide on structuring the project, router implementation, API controller creation, and mapping HTTP actions to SQL operations.Recaps the importance of REST API in product development, best practices, and invites questions from the audience.
Who Am I
• PHP Developer & Consultant
• Reviewed “Testing with Qunit”
• Helped to bring out thesis on “Business
Prospective of cloud computing”
• Founder of Website “WebGunny.com”
RIP Jun 2010 - Dec 2011
3.
In this talk...
• Why REST API is a heart of every product
• REST API – As developer UI
• Best Practices of REST API
• REST API in codeigniter
Let’s Start withbest practices
API End Point :
https://www.YourApp.com/Api/
OR
https://Api.YourApp.com/
Finally Format:
https://www.YourApp.com/Api/ResourceName
9.
Identifying resources
•You can make the resources more sensible
based on your product
• For example
– Tasks
– Comments
– Notifications
– Users
– Projects
– Files
Make Use ofHTTP Verbs
• GET /task - Retrieves a list of task
• GET /task/12 - Retrieves a specific task
• POST /task - Creates a new task
• PUT /task/12 - Updates task #12
• PATCH /task/12 - Partially updates task #12
• DELETE /task/ - Deletes all task
• DELETE /task/12 - Deletes task #12
12.
Map the relationships
• GET /task/12/comments - Retrieves list of comments
for task #12
• GET /task /12/comments/5 - Retrieves comment #5 for
task #12
• POST /task /12/comments - Creates a new comments
in task #12
• PUT /task /12/comments/5 - Updates comments #5 for
task #12
• PATCH /task /12/comments/5 - Partially updates
comment #5 for task #12
• DELETE /task/12/comments/5 - Deletes comment #5
for task #12
13.
Search Sort &Filter
• GET /tasks?sort=-priority - Retrieves a list of
task in descending order of priority
• GET /tasks?sort=-priority,created_at -
Retrieves a list of tasks in descending order of
priority then by date created
14.
Aliases for commonqueries
To make the API experience more pleasant for
the average consumer
GET /tasks?status=completed
GET /tasks/recently_completed
15.
Allow the fieldsto be selected
The API consumer doesn't always need the full
representation of a resource.
GET /task?fields=id,title,updated_at
16.
Paging of data
Paging makes the API fast & responsive
GET /notification?page=1&per_page=50
17.
Return full resourceafter action
• A PUT, POST or PATCH call may make
modifications to fields
• Return the updated (or created)
representation as part of the response.
• Prevent an API consumer from having to hit
the API again
18.
Auto loading related
resources
{ "id" : 12,
“TaskName" : "I have a question!",
"summary" : "Hi, ....",
"customer" : { "name" : "Bob" },
assigned_user: { "id" : 42, "name" : "Jim", }
}
19.
Make Error MessageFriendly
• The API should always return sensible HTTP
status codes
• 400 series status codes for client issues & 500
series status codes for server issues
• API should standardize that all 400 series errors
come with consumable JSON error
representation
{ "code" : 1234,
"message" : “task field validation failed ",
"description" : “Due date is not set"
}
REST API inCodeigniter
UI/ Controller
Your App
Your API
Rest Client
24.
What we need
• Codeigniter
• chriskacerguis/codeigniter-restserver
• Router implementation
25.
Structuring the project
/application
/controller/
api/ //For all api controllers
/libraries //For the third-party libraries
REST_server.php
Format.php
/config //For all config files
Router.php
Rest_server.php
Creating a firstAPI controller
require(APPPATH . '/libraries/Rest_Service.php');
class task extends REST_Service{
public function index_get() { //Logic }
public function index_post() { //Logic }
public function index_put() { //Logic }
public function index_patch() { //Logic }
public function index_delete() { //Logic }
}
28.
Every Function has2 Reaction
public function index_get() {
if($this->get('id'))
{
//Application Logic
$this->response($results,$code);
}
else
{
//Application Logic
$this->response($results,$code);
}
}
29.
HTTP Action VsSQL
• Get (select)
– Get All
– Get by ID
• Post (Insert)
• Put (update all fields )
• Patch (update selected fields)
• Delete (delete)
– Delete All
– Delete by ID
30.
Summary
• RESTAPI is heart of product
• REST API is a developer UI
• Follow the best practices of REST API
• Use “chriskacerguis/codeigniter-restserver” to
implement REST in codeigniter
#3 I am a PHP Developer & Consultant
Have reviewed “Testing with Quinit”
Helped to bring out thesis on Business Prospective of cloud computing
Founder of webgunny.com – A iGaming portal whose revenue is based on advertisement. However, I shutdown that site after 1.8 years of operation
#5 Let’s say you started building your next product – A task management system.
Users can login, add tasks, assign it to people in their team, discuss on a task, change status & so on.
You built it in MVC – It’s a Nice Architecture and launched it.
Around 10 users started using it...Few users became a fan of your app – A loyal users
They demanded the app to be on Mobile devices with good native experience.
Now the problem arises. You must rewrite the business logic for ios ,android, firefox os & so on.
It’s like redoing the whole app in all the devices!!! That’s wired!!!
Did we had made something which would have escaped us from this problem ?
Yes, you should have implemented a REST API – Representational state transfer Application Programming Interface
All your application, be it a desktop app, web app, mobile app will all your API to run your business logic
Once the API is being implemented you can integrate with Google Glasses, iWatches anything you name....
#6 Now all your loyal users are happy. You customers increased.
Soon one of your customer want to integrate your app with his home grown app
Now you can ask your customer to use your API to integration
Of course, with some authentation & authorization
#7 But...here is a catch..you actual API customer is not the end user. He is a developer
Now the question is to how to make the developer happy with your API
Simple answer – Build a developer friendly API
#8 It’s definitely not a rocket science.
It’s just a common sense with some intelligence
#12 Build your API around HTTP Action – GET, POST, PUT,PATCH,DELETE
In example you can see the first one retrieves all the tasks
#13 Next , Map the relationship
First example retrives all the comments on a task #12
#14 Build a mechanism to search/sort/filter
You can use some common sense here and build a aliases API call
For example build a separate API call to get all recently completed tasks
#18 Let your API return full details about the task on every operation.
Say you updated a task by calling a API request.
Instead of just return Boolean if the activity is successful
Just return full details of the task
This will reduce the work of the developer to hit the API gain to get the updated data
#19 It’s a best practice to related data.
For example, instead of just returning the assigned user ID
It Return the whole user object/resource along with the user name.
This will also reduce the number of hits to API server
#20 Make errors friendly to understand. API should always return sensible HTTP status code
200 – For successfully operation
400 – For errors data validation etc
500 – For server errors
Also return the standard error object with the proper message stating why the operation failed.
It would be good if you can provide a code for all your errors.