I'm planning a small web application project which will consist of both a website (using PHP) and in the future a mobile application. I want to implement a RESTful API (using PHP) to communicate with the mobile app. But since the API and the website will both be written in PHP and hosted on the same server, it seems a bit odd to make HTTP calls from the website to the public API (or isn't it)?
Anyway, I am considering putting a layer between the API and the business logic, basically just consisting of an object that exposes the same API as the public RESTful API, but as a PHP object that can be accessed directly from the website.
Is this a good or bad idea? Why?
Is this a well known pattern? If so, what is it called?
I found some sites proposing a similar structure and calling it "API Gateway Object", but I'm not sure if that is an actual well-known pattern or just something they came up with tho.
Here's a sketch of what I have in mind:
Good question (answer) ... not sure it is the right kind for this site. I use exactly that pattern, which I ended up rolling out after hard-fought battles with other architectural approaches/frameworks i.e. I dont know its name.
some pros :
Turns out it is also extremely useful for testing, climbing up the abstraction ladder can be easily structured and exercised with your favorite testing toys.
Your mobile data architecture can be a straight isomorph of the Gateway Object model.
It nicely decouples for straight php access AND it still permits you to keep some things in play when it matters : auth, logging, traceability of database access.
It future proofs your design : although it may seem silly at the moment, you may find that you will eventually need to have www and mobile presentations served from different instances. Migrating your php presentation to use RESTful API will be a cinch if you do this right.
An example : Say I have a Message object, this object will have a number of 'normal' classes:
Message : the plain-old-php-object, no side effects, no persistence
MessageDAO : the persistence manager for Message. basic CRUD, no business logic, just elementary CRUD
MessageWF : the workflows offered by the business logic
IBMessageSpec : a specification for a message
OBMessage : the representation of the message that I wish to send to the caller
I use a DI container to inject in each of the above the specifics of the context.
In my Mobile , I have OBMessageSpec wihch is essentially an IBMessageSpec, and IBMessage which maps the servers's OBMessage. That code is pretty much re-useable to multiple instance types, and apps.
It is OK idea. You could provide an API for internal PHP usage via some API Gateway Object and expose RESTful API, that uses same API Gateway Object. It may be named Adapter, because it adapts your php API to be used by external services via HTTP.
But why do you need something to be known pattern to use it ? It perfectly lays on your needs, this architecture allows you to keep your modules consistent and avoid duplications of logic.
You can use RESTful on PHP side, it would be slower, but more flexible - maybe in future you'll need to rewrite backend with some other language - you don't need to change frontend!
So, it is up to you to decide, what is more preferable for you, it is not about patterns.
Related
Im confused regarding the need of REST for a web service.Im a noob when it comes to web service,the scalability etc.
This is my requirement
-Need to fetch some data eg:names of students in a class and their photographs plus their address and stuff
-There is no authenciation/Tokens required since the data is publicly available
My question is
-Do i need to use REST for this? Will MYSQL+PHP Webservice that communicates using HTTP GET and POST do the job?
-If i go with this approach will this affect the performance of the app,when there is bulk data and will it scale?The maximum number of users that may be using the app is just 50 at a time.
-Does REST offer significant advantages,since i dont know JSON and stuff,will it payoff the learning curve?
It's better to use REST. You can just post your data as HTTP or as JSON and then process this data in your function and return result as JSON .
I recommend you to use CakePHP or Yii because it's easy to use.
In case of bulk transaction you can use MongoDb as your database.
What I would say is that REST describes a way to leverage HTTP features and use them in an optimal way. Otherwise you don't have to use all the REST mechanisms to implement a RESTful application.
I think that this link could help you to understand how to implement a Web API (i.e. a RESTful application):
Designing a Web API: https://templth.wordpress.com/2014/12/15/designing-a-web-api/
Here are my answers to your questions:
REST doesn't require an authentication to access resources. However REST integrates authentication mechanisms based on the HTTP header Authorization.
REST describes good practices in using HTTP but of course, you're free to use it as you want ;-) REST recommends to use the HTTP methods for what they actually are. To be short, GET to retrieve data, PUT / POST to update data (POST mainly to add data and PUT to update them) and DELETE to delete data. POST can also be used for what we can see as actions. REST also uses specific URIs with path variables. If I use your example, the URI for a list of students within a class would be: /classrooms/<classid>/students. REST also define a mechanism to request specific content format such as JSON based on the header Accept. In fact, you're generally familiar with most of these aspects if you implement Web applications for some years and REST provides you a way to design your application to leverage them at best.
Regarding performance, I would say no. One of the key aspect of REST is that RESTful applications are stateless. No state must be handled on the server side. This allows applications to scale more readily. I don't see any reason for bad performances regarding bulk updates. In fact, it's up to you to handle them. REST leaves the choice of the data format content sent to the server and the way to handle them efficiently on the server side. You can consider using either synchronous and asynchronous approach. For the asynchronous approach, you should return an HTTP status code 202. This approach can allow you to control the work load of updates for concurrent users. You could add the bulk updates to a queue and handle them after one per one in a separate process or thread. An example of RESTful application that uses bulk updates is ElasticSearch. See this link: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.
The main advantage of REST is that it allows you to leverage HTTP mechanisms at best. Another thing that comes to mind is that there is now some tools allowing you to generate client kits to consume your application and generate documentations about the contract of your RESTful applications. See Swagger (Swagger, Swagger UI, Swagger Codegen) and RAML. These links can help you: http://swagger.io/ and http://raml.org/. Another tool, Restlet Studio (http://studio.restlet.com/#/), can help you to understand all these concepts since it comes with a sample application. Regarding the learning curve, I don't think that it's too much important since if you already implement web application, you know most of concepts.
Regarding the format you would use for content, JSON seems to be a good fit. However REST doesn't enforce any content kind. It provides a mechanism to request a specific content (Conneg, i.e. content negotiation based on the header Accept) but you don't have to use it. REST let you the way to manage this content within your application.
Hope it heps you,
Thierry
You can implement any protocol you want to do that, but using REST ensure you are following a common procedure which will make your application more maintainable.
The amount of resources used depends how do you implement the queries and responses on the server-side.
You should learn that, it will improve your knowledge as you can learn together other patterns (gateway, repository, MVC) to make your server-side professional and maintainable.
My suggestion for your application is implementing the server-side using a framework such as Laravel (I recommend), CakePHP or similar. I say that because your app seems to be just interaction with pre-defined models.
I am creating an applicaton in PHP with MVC based framework. I am exposing a web API for the mobile apps.
The same mobile interface is to be created in web application also. So:
For creating the web interface, can I use the API created for mobile app with HTTP request?
OR
Model methods are exposed, so can we use the model instead of calling and connecting with the API in same server?
What is the best practice?
It depends , if it is your internal product, and you are the only user of API, it is better to expose function base API. eg: addUser, deleteUser.
If you want some one else to use the API and create some application (with different logic depending on their own need) give them model based access. As far as I know functional API's are generally created and exposed. Because this kinds of API saves the number of webservice call and hides the logic underneath it.
edit
if you mean calling the webservice internally ... Ideally design should be such that ..their should be a delegate method that consists of core logic, then that core logic function can be called from your api as well as controller. Calling webservice internally will be a unnecessasary performance overhead. Though you can do that in small size application, but is not at all good solution.
If your model layer holds business logic, though It should be Ideally a seperate layer ...then you should consider using model.
What's the difference between a REST system and a system that is RESTful?
From a few things I've read most so called REST services are actually RESTful services. So what is the difference between the two.
Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web.
RESTful is typically used to refer to web services implementing such an architecture.
REST based Services/Architecture vs. RESTFUL Services/Architecture
To differentiate or compare these 2, you should know what REST is.
REST (REpresentational State Transfer) is basically an architectural style of development having some principles:
It should be stateless
It should access all the resources from the server using only URI
It does not have inbuilt encryption
It does not have session
It uses one and only one protocol - HTTP
For performing CRUD operations, it should use HTTP verbs such as get, post, put and delete
It should return the result only in the form of JSON or XML, atom, OData etc. (lightweight data )
REST based services follow some of the above principles and not all
RESTFUL services means it follows all the above principles.
It is similar to the concept of:
Object oriented languages support all the OOP concepts, examples: C++, C#
Object-based languages support some of the OOP features, examples: JavaScript, VB
Example:
ASP Dot NET MVC 4 is REST-Based while Microsoft WEB API is RESTFul.
MVC supports only some of the above REST principles whereas WEB API supports all the above REST Principles.
MVC only supports the following from the REST API
We can access the resource using URI
It supports the HTTP verb to access the resource from server
It can return the results in the form of JSON, XML, that is the HTTPResponse.
However, at the same time in MVC
We can use the session
We can make it stateful
We can return video or image from the controller action method which basically violates the REST principles
That is why MVC is REST-Based whereas WEB API supports all the above principles and is RESTFul.
"REST" is an architectural paradigm. "RESTful" describes using that paradigm.
As Jason said in the comments, RESTful is just used as an adjective describing something that respects the REST constraints.
REST stands for representational state transfer. That means that state itself is not transferred but a mere representation of it is. The most common example is a pure HTML server based app (no javascript). The browser knows nothing about the application itself but through links and resources, the server is able transfer the state of the application to the browser. Where a button would normally change a state variable (e.g. page open) in a regular windows application, in the browser you have a link that represents such a state change.
The idea is to use hypermedia. And perhaps to create new hypermedia types. Potentially we can expand the browser with javascript/AJAX and create new custom hypermedia types. And we would have a true REST application.
This is my short version of what REST stands for, the problem is that it is hard to implement. I personally say RESTful, when I want to make reference to the REST principles but I know I am not really implementing the whole concept of REST. We don't really say SOAPful, because you either use SOAP or not. I think most people don't do REST the way it was envisioned by it's creator Roy Fielding, we actually implement RESTful or RESTlike architectures. You can see his dissertation, and you will find the REST acronym but not the word RESTful.
REST is an style of software architecture for distributed software
Conforming to the REST constraints is referred to as being ‘RESTful’.
Very used today to build web services as an alternative to SOAP.
Here you have some links to check
http://en.wikipedia.org/wiki/Representational_State_Transfer
http://www.computerworld.com/s/article/297424/Representational_State_Transfer_REST_
http://www.ibm.com/developerworks/webservices/library/ws-restful/
thanks for the answers.
Read this article by Alex Rodriguez which suggests that a RESTful web service has 4 basic characteristics which are:
Use HTTP methods explicitly.
Be stateless.
Expose directory structure-like URIs.
Transfer XML, JavaScript Object Notation (JSON), or both.
Representational State Transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. The term Representational State Transfer was introduced and defined in 2000 by Roy Fielding1[2] in his doctoral dissertation. Fielding is one of the principal authors of the Hypertext Transfer Protocol (HTTP) specification versions 1.0 and 1.1.
Conforming to the REST constraints is referred to as being ‘RESTful’. Source:Wikipedia
Web services are essentially web sites whose content is consumed by computer programs, not people. REST is a set of architectural principles that stipulate that web services should maximally leverage HTTP and other web standards, so that programs gain all the good stuff that people already can get out of the web. REST is often contrasted with SOAP web services, and other "remote procedure call" oriented web services.
Stefan Tilkov's presentations on REST at Parleys.com are quite good, especially this one.
For a book, you can't get any better than Richardson and Ruby's Restful Web Services.
A service based on REST is called a "RESTful service".
Source I rely on posting that: Dr.Dobbs Archive
There are 4 levels of API defined in the Richardson Maturity Model. These are defined as:
level 0: any system that has a single endpoint for all its apis(SOAP or RPC fall in this category). Level 0 apis can also resemble "commands".
level 1: a ResourceUri described system. This is a system that defines multiple entity-based URIs (instead of having a single endpoint like a level 0 systems would). These URIs can use different http actions (POST, GET, PUT, etc) to implement different actions against that resource.
level 2: aka level 1 w/ a compliant use of Standard HTTP methods/verbs and multi status code responses
level 3: aka level 2 plus HATEOAS (hypermedia included in the response which describes additional calls you can make)
While levels 1, level 2, and level 3 can be considered as REST systems, only the stricter levels (aka level 2 and level 3) are considered to be RESTful.
So essentially all RESTful apis are REST apis, but not all REST apis are RESTful
definition of the Richardson Maturity Model
Coming at it from the perspective of an object oriented programming mindset, REST is analogous to the interface to be implemented, and a RESTfull service is analogous to the actual implementation of the REST "interface".
REST just defines a set of rules that says what it is to be a REST api, and a RESTfull service follows those rules.
Allot of answers above already laid out most of those rules, but I know one of the big things that is required, and in my experience often overlooked, as that a true REST api has to be hyperlink driven, in addition to all of the HTTP PUT, POST, GET, DELETE jazz.
A "REST service" and a "RESTful service" are one and the same.
A RESTful system is any system that follows the REST conventions as defined in the original document that created the idea of RESTful networked applications.
It's worth noting there are varying levels of RESTfulness. Overall, REST is a style, not a standard, so there is room for interpretation based on needs. one example is hierarchical resource URLs (e.g. /things/ID/relatedthings) vs flat URLs (e.g. /things/ID and /relatedthings?thing=ID)
Think of REST as an architectural "class" while RESTful is the well known "instance" of that class.
Please mind the ""; we are not dealing with "real" programming objects here.
REST(REpresentation State Transfer) is an architecture using which WebServices are created.
and
RESTful is way of writing services using the REST architectures. RESTful services exposes the resources to identify the targets to interact with clients.
REST is an architectural pattern for creating web services. A RESTful service is one that implements that pattern.
I have different questions about a full architecture idea. I hope someone with great experience could help me out because I am pretty much getting stuck in all possibilities.
I'm planning to rewrite a community website. Our customer wants to make use of native mobile apps in the future. So I will need to take this into account. Because of this I have decided to create a 100% REST API architecture based on the PHP framework Kohana. I have choosen Kohana because this makes scaling the internal API to a other server very easily without much extra effort. (Kohana threats internal url requests not as HTTP so there isn't much overhead in the beginning and can scale to HTTP with some minor code changes).
At first the API will be private, but later on we might make it public to let more services connect to us easily.
De basic REST structure is as follow:
/cats
/cats/1
/cats/1/custom
'custom' could be 'childs' for instance.
same goes for:
/ads
/bids
/users
/banners
etc..
These are perfect entities for the API because the mobile app will definitely use all this functionality.
So we can conclude the core of the website is REST. So basically I want to make the website a client of the API just like the native app in the future. This way maintenance seems much easier.
What worries me though is the fact that there is much more than this (managing uploaded files, invoicing, automails for invoicing, automails for ads and so on). Uploading files needs to go through the website to the API. Is this common practice? If I do not do this, the website would do upload logic, which makes the site no client anymore and the app itself. Hence the mobile app can't even upload and both API and website need to know the upload folder (duplicate logic).
I thought of creating the following modules:
community-api
community-website
Api seems to be the core then. But.... what about cronjobs etc? Actually they should not be part of the website, as this is just a 'client'. I feel they should interact directly with the model or API. So basically the API gets more like a gateway to the core and thought I need this:
community-core
Models
Cronjobs
Auto Mailings (part of cronjobs)
Invoices etc
community-api
Interact with models in core through HTTP
community-website
Website
Admin
The core cronjobs are a exception to the REST structure. They are the only one that can change data without going through the api. At least that was my idea because they belong in the core and API is on top of the core.
But by design that seems just wrong. Manipulating should only go through the API!
Alternative:
community-core
Models
community-api
Interact with models in core through HTTP
community business
Cronjobs
Auto Mailings (part of cronjobs)
Invoices etc
community-website
Website
Admin
This look better by design to me.
(source: mauserrifle.nl)
Main Questions
1)
Should cronjobs manipulate through the API or Core models?
2)
My invoice cronjob needs a template pretty much the style of main website of course. But if my cronjob is part of business or core it won't have knowledge of my main website. What makes sense to solve this?
3)
My website will be using mustache as a template engine. (both php and javascript can parse these templates). I thought using the api directly for ajax calls but then realized:
The site gets data from api, formats timestamps to dates (Y-m-d) for the template and then renders. If I let javascript call the api directly, javascript must have logic too (formatting). This is duplicate code! Feels like the only solution is calling the website for ajax (which calls the api and formats) and returns the formatted json. Am I right?
But.... simple calls like deleting a ad can go through the api directly (e.g. DELETE: /ads/1
I get a mix of calls....
Any better solution for this?
4)
Overall: Is my architecture too complex? Any alternatives I should consider?
I would love to hear your feedback!
Once I've heard that a good way to develop a web application is to develop an API-Centric Web Application. The thing is, to me, if you couple the main service to the public API, building an API-Centric application, you lose the whole point of developing a public API at all.
This doesn't seem logical to me.
Yes, the API and the website and what ever might come next are separate things and website should be a client to the API itself but since it will simplify things greate, I believe that you should RE-USE the domain-classes to build and base your web-site logic. This way you can use all the same code base and handle all your issues including ads, invoicing and of course file uploads with ease.
For the public API, it should be on a separate box if possible re-using the same domain classes but with different authentication methods so that whatever problem might occur, it won't affect the main service.
Your cron-jobs should only be used to fire the call through the API itself and those calls should be made on the main app (website through the API)
If you build your website without repeating-yourself, as in, using the same code as the base and wrapping the web-app around it, you won't have the issue raising in q#2.
Same thing applies for question number 3. If you wrap the website around the API, the website can use the api itself without being a separate entity.
Your architecture seems complex but if you do these things, it will be simple. ;-)
Good luck!
REST is just one way to initiate a request. Your core code that processes the request shouldn't be tightly coupled to the REST interface, or HTTP for that matter. I would advise designing your REST API as a simple mapper to an include file or something similar. Your cron could then bypass the whole REST API and just include the file directly. Separate the request interface from the code that does the actual processing.
I'm looking for some thin layer on top of handling HTTP requests that can easily do routing to different backends, based on the uri / rest verb / actual service location / .... This layer should also handle encoding into whatever the requested format is (xml / json / returning binary data / etc.).
The most important point though is to make it pluggable into some backend - whether it's a message queue, job dispatcher, external process, or something completely different. They should be handled with minimal wrapper for the needed message translation.
So basically, that would be a customisable request dispatcher with some magic on top. Does something like that exist as a separate application now?
Edit: Almost forgot - it would be great if it was written in PHP... but if something else matches the description, I'd have a look too.
Don't know about PHP, but if Java and/or Python are acceptable options for you, you should take a look at RESTx, which was designed for the simple and fast creation of RESTful services. RESTx is fully open source, GPLv3 licensed.
I agree that many frameworks are all about object creation and mapping, which often can be very annoying and get in the way. RESTx, however, is about the data, the automatic conversion of content types and so on. With RESTx you can write custom components in either Java or Python. These components can take care of access to databases, custom APIs, legacy data, cloud services, etc. RESTx examines the code and automatically produces a self documented, discoverable, RESTful API. It's all links you can follow. Take a look at how to take a tour of the server with a web browser.
The key is that you can POST parameter sets to those components which are then stored and accessible under a new URI. You access the URI, the parameters get applied to the component and you get the output back. Thus, you can rapidly create new RESTful web services and resources. You can access other resources easily from within your component's code and it doesn't cause an additional HTTP request.
I'm the lead developer for RESTx, so if you have any questions about it, please contact me on the forums (links to those are on our web site).
Zed Shaw of Mongrel fame is attempting to do just this. He's creating Mongrel2 (still in development), essentially a universal frontend for web application backends. It allows you to plug in any program that can send and receive 0MQ or HTTP messages like a reverse proxy.
It also uses a sane configuration file system: SQLite. No more messing around with Apache config files with weird syntax.
It's written in C, so it may not be as easy to deploy as a language like PHP, but it certainly scales very well.
If you're not satisfied with Mongrel2, it's relatively easy to roll your own. I've used nodejitsu's node-http-proxy for one of my own projects. It's simple and fast. Plus, you can write your routing rules using regular old if statements.
I'm new to StackOverflow so it won't let me embed more than one hyperlink, haha.