Creating a simple REST API in php
Basics of REST API Design
REST architecture will be useful to build client/server network applications. REST represents Representational State Transfer.It basically works on HTTP protocol.
Following are the list of things should be considered while building a REST api.
» HTTP Methods
A well-designed RESTful API should support most commonly used HTTP methods (GET, POST, PUT and DELETE). There are other HTTP methods like OPTIONS, HEAD but these are used most often. Each method should be used depending on the type of operation you are performing.
|GET||To fetch a resource|
|POST||To create a new resource|
|PUT||To update existing resource|
|DELETE||To delete a resource|
» HTTP Status Code
HTTP status codes in the response body tells client application what action should be taken with the response.
For an example: if the response code 200, it means on the server side the request is processed successfully and you can expect updated data in the response. As well if the status code is 401, the request is not authorized. An example cause for 401 could be api key is invalid.
|500||Internal Server Error|
» URL Structure
In REST design the URL endpoints should be well formed and should be easily understandable. Every URL for a resource should be uniquely identified. If your API needs an API key to access, the api key should be kept in HTTP headers instead of including it in URL.
For an example:
GET http://abc.com/v1/tasks/11 – Will give the details of a task whose id is 11
POST http://abc.com/v1/tasks – Will create a new task
» Content Type
The Content Type in HTTP headers specifies the kind of the data should be transferred between server and client. Depending upon the data your API supporting you need to set the content type.
For an example: JSON Mime type should be Content-Type: application/json, for XML Content-Type: application/xml.
» API Key
If you are building a private API where you want to restrict the access or limit to a private access, the best approach is to secure your API using an API key.
For an example:
GET http://example.com/article&api_key=12345 – Will give the details of a task whose id is 11