How to Build a RESTful API Web Service with PHP
2015-08-17 13:42
671 查看
http://markroland.com/blog/restful-php-api/
When I built my new online portfolio, I knew I wanted to create a RESTful API to easily access my data. Here’s how I did it.
I started developing my first API nearly 2 years ago. At that time I couldn’t find any simple examples, so I reverse engineered my experiences as a user of the Twitter and Flickr APIs. Over the years I have refined and distilled my API “template” so that I
can add a web service to a site with minimal effort.
After I started writing this post I read “Create Your API with Restler” by Richard
Askew in the December 2012 issue of .Net magazine. This is a really good article that confirms many of the techniques that I have been doing and have included in my sample code. Like many of the other API “How To” articles I’ve seen, this article relies
on a library of dense code. That’s not a bad thing, but I think there’s a lot to be said for the simplicity of a single script with no included files, especially when learning something for the first time. With that in mind, I’m presenting this post as a simple,
startup template for creating a RESTful API using PHP and no additional libraries.
As I started, it was simple enough to create some web service endpoints that would return data, but it took me a while to refine my code so that it would do things like set the correct HTTP Content-Type header, return useful HTTP response codes and provide
multiple data formats. Taking what I have learned as I developed four similar web services, I have distilled my API script into four major parts: Initialization, Authorization, Request Processing and Response Delivery.
The API environment is composed of 2 files, an application script (index.php) and a URL redirection file (.htaccess). The URL redirector will allow users to connect to the API using pretty URLs. The .htaccess file requires the mod_rewrite module on an Apache
server. The API can still work if mod_rewrite is not available, but URLS will need to be formatted like:
“/api/?method=hello&format=json”
instead of the prettier:
“/api/hello.json”.
The first part of the API application script (index.php) is basic initialization. This part of the script defines the API’s settings, such as whether a secure HTTPS connection is required and whether the API is username and password protected. Additionally,
the API initialization will define the API response codes. Finally, the initialization contains a function definition for the “deliver_response” function. This function controls the HTTP response codes, sets the Content-Type header and formats the data as
JSON, XML or HTML. The “deliver_response” function is described in more detail in Step 4.
Authorization is an option that can be used to restrict access to the web services. This part of the code contains two “if” statements that optionally perform security tests based on the settings in Step 1. An advantage of requiring users to connect using HTTPS
requests is that your data will be sent using encryption. This could be necessary if the web service is sending sensitive or personal information. The second “if” statement tests for the existence and authentication of a username and password.
The third step of the web service script is the meat of the API. This is where the the requested data is gathered by the application. In this example, the response data is simply a predefined “Hello World” message, but this could easily be replaced with code
to retrieve information from a database or any other source, even another API! An API status code is also defined, as is an HTTP status code.
The final action of the web service script is to deliver a response in the format defined in the HTTP request. This API templates supports 3 different formats: JSON, XML and HTML. When I first started working with web services I thought XML was amazing because
it was human-readable and could be formatted to meet any application’s needs. Unfortunately, the human-readiblity of XML means that it is more difficult to parse programmatically. On the other hand, PHP and JavaScript have such simple parsing options for JSON,
that I would now be hard-pressed to choose formatting data using anything other than JSON. Returning the results as plain HTML can be beneficial in some cases, so I’ve included that option, too.
The “deliver_response” function first defines several basic HTTP response codes. After the response codes are defined, the
data is formatted according to the value of the “format” variable in the request’s query string. The JSON response is complete, however the XML and HTML responses are only complete for simple string responses, and are not currently designed to handle arrays
or data objects. You will want to tailor these to your specific needs.
Here is the complete index.php script.
There you have it, a simple PHP API Web Service script. This is just a shell that can be filled in with your specific application needs. I hope you find it as useful as I have. If you have any questions or comments you can reach me on twitter @rolandojones.
Here are sample some endpoints and their responses.
http://markroland.com/project/php-api-template/demo/hello.json
http://markroland.com/project/php-api-template/demo/hello.html
http://markroland.com/project/php-api-template/demo/hello.xml
API, JSON, PHP, XML
When I built my new online portfolio, I knew I wanted to create a RESTful API to easily access my data. Here’s how I did it.
I started developing my first API nearly 2 years ago. At that time I couldn’t find any simple examples, so I reverse engineered my experiences as a user of the Twitter and Flickr APIs. Over the years I have refined and distilled my API “template” so that I
can add a web service to a site with minimal effort.
After I started writing this post I read “Create Your API with Restler” by Richard
Askew in the December 2012 issue of .Net magazine. This is a really good article that confirms many of the techniques that I have been doing and have included in my sample code. Like many of the other API “How To” articles I’ve seen, this article relies
on a library of dense code. That’s not a bad thing, but I think there’s a lot to be said for the simplicity of a single script with no included files, especially when learning something for the first time. With that in mind, I’m presenting this post as a simple,
startup template for creating a RESTful API using PHP and no additional libraries.
As I started, it was simple enough to create some web service endpoints that would return data, but it took me a while to refine my code so that it would do things like set the correct HTTP Content-Type header, return useful HTTP response codes and provide
multiple data formats. Taking what I have learned as I developed four similar web services, I have distilled my API script into four major parts: Initialization, Authorization, Request Processing and Response Delivery.
Set Up Your API Development Environment
The API environment is composed of 2 files, an application script (index.php) and a URL redirection file (.htaccess). The URL redirector will allow users to connect to the API using pretty URLs. The .htaccess file requires the mod_rewrite module on an Apacheserver. The API can still work if mod_rewrite is not available, but URLS will need to be formatted like:
“/api/?method=hello&format=json”
instead of the prettier:
“/api/hello.json”.
.htaccess:
Step 1: Initialization
The first part of the API application script (index.php) is basic initialization. This part of the script defines the API’s settings, such as whether a secure HTTPS connection is required and whether the API is username and password protected. Additionally,the API initialization will define the API response codes. Finally, the initialization contains a function definition for the “deliver_response” function. This function controls the HTTP response codes, sets the Content-Type header and formats the data as
JSON, XML or HTML. The “deliver_response” function is described in more detail in Step 4.
Step 2: Authorization
Authorization is an option that can be used to restrict access to the web services. This part of the code contains two “if” statements that optionally perform security tests based on the settings in Step 1. An advantage of requiring users to connect using HTTPSrequests is that your data will be sent using encryption. This could be necessary if the web service is sending sensitive or personal information. The second “if” statement tests for the existence and authentication of a username and password.
Step 3: Process Request
The third step of the web service script is the meat of the API. This is where the the requested data is gathered by the application. In this example, the response data is simply a predefined “Hello World” message, but this could easily be replaced with codeto retrieve information from a database or any other source, even another API! An API status code is also defined, as is an HTTP status code.
Step 4: Deliver Response
The final action of the web service script is to deliver a response in the format defined in the HTTP request. This API templates supports 3 different formats: JSON, XML and HTML. When I first started working with web services I thought XML was amazing becauseit was human-readable and could be formatted to meet any application’s needs. Unfortunately, the human-readiblity of XML means that it is more difficult to parse programmatically. On the other hand, PHP and JavaScript have such simple parsing options for JSON,
that I would now be hard-pressed to choose formatting data using anything other than JSON. Returning the results as plain HTML can be beneficial in some cases, so I’ve included that option, too.
The “deliver_response” function first defines several basic HTTP response codes. After the response codes are defined, the
data is formatted according to the value of the “format” variable in the request’s query string. The JSON response is complete, however the XML and HTML responses are only complete for simple string responses, and are not currently designed to handle arrays
or data objects. You will want to tailor these to your specific needs.
Here is the complete index.php script.
index.php:
Conclusion
There you have it, a simple PHP API Web Service script. This is just a shell that can be filled in with your specific application needs. I hope you find it as useful as I have. If you have any questions or comments you can reach me on twitter @rolandojones.Here are sample some endpoints and their responses.
http://markroland.com/project/php-api-template/demo/hello.json
相关文章推荐
- UI设计师不可不知的安卓屏幕知识
- Windows 7 SP1 多国语言包(MUI language packs)官方下载
- UI星辰:UI代码创建视图和Label设置
- 栈 Deque
- poj 3080 Blue Jeans 暴力
- UILabel 多行文本及动态计算其高度
- UIView与CALayer的区别
- in query_vcvarsall raise ValueError(str(list(result.keys()))) ValueError: [u'path'] 解决
- hdu 5301 Buildings 2015 Multi-University Training Contest 2
- iOS7 UIKit动力学-碰撞特性UICollisionBehavior 上
- iiOS开发UI篇--IOS动画(Core Animation)总结
- QueryInterface
- AVplayer的使用详解 完整注释
- iOS 9界面适配利器:详解Xcode 7的新特性UIStackView
- [Tue, 11 Aug 2015 ~ Mon, 17 Aug 2015] Deep Learning in arxiv
- This inspection controls whether the Persistence QL Queries are error-checked
- Android_UI不同dpi下的图片选择
- 快速排序法 quickSort---java
- easyui 窗口 滚动条 固定位置显示
- ubuntu12.04 + fuerte ROS下安装xtion pro live 显示图像