RESTfull website in php [duplicate] - php

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.

Related

Architecture of application with public RESTful API + local access to API

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.

How to implement Restful Objects specification in MVC/Symfony project

I have been glancing at a RESTful specification available on http://restfulobjects.org (direct link to spec here). It is a little different from other things I have seen, but it makes sense, and having examples and clear specifications makes my development a lot simpler.
According to the standard, the URIs will be like:
api.example.com/object/user/31
api.example.com/object/user/31/properties/username
api.example.com/object/user/31/collections/channels
api.example.com/object/user/31/actions/someFunction
api.example.com/object/user/31/actions/someFunction/invoke
See this answer for a brief explanation of the structure. It is quite clear.
Note: This is not a discussion whether or not services/actions can be
represented as resources. There is a good discussion on that topic
here: http://www.infoq.com/articles/Intro_Restful_Objects. Look towards the end of the comments section.
My project is still on the drawing board, and most design elements up for grasp. I will however be using Symfony. I have my entities, and I have some services that act on those entities, and I have controllers to define what the services will do in a specific context.
And so to my actual questions:
...the Restful Objects spec is not based on the MVC pattern - it makes
no assumptions about the architecture of the server that implements
the API. In the URL:
~/objects/customers/31/actions/lastOrder/invoke
the 'actions/lastOrder' is not specifying a controller action, it is
specifying an action (i.e. a method) on a domain object (customers/31)
How do I structure my controllers in the most efficient way if I want to use the specification in an MVC application? Considering that the controllers would somehow serve different resources (objects, services, domain-types) as well as different representations of that resource. What are my layers?
Update Do I have e.g. a customer controller? An generic object controller? A useraction controller?
Do I need to rethink my whole entity/services approach? i.e. the solution for how to implement this is beyond the controller structure? (I fear it is, and then I do not know my next step)
For simplicity/efficiency I would like to make use of the FOSRestBundle and NelmioAPiDocBundle. I believe this can be done, but I then am concerned the spec will only serve as a url template for me, and not being implemented in my logic/design since I have to massage my framework to fit the URL somehow.
Please excuse my ignorance if this question has an obvious answer. I am new to RESTful APIs. If it comes down to a subjective perspective on implementation model, please give me some pointers, because I am currently at a loss for how to approach this.
From the "What is Symfony2 ?" article of Fabien Potencier:
Is Symfony2 an MVC framework?
If you look around, every single framework seems to implement the MVC pattern. And most of them are advertised as MVC frameworks... but not Symfony2. Have a look at the documentation, and you will see that the MVC pattern is only mentioned once or twice, but Symfony2 is never defined as being an MVC framework.
A bit later in this post:
Symfony2 is an HTTP framework; it is a Request/Response framework.
That's the big deal. The fundamental principles of Symfony2 are centered around the HTTP specification.
...
Sometimes, you just need a way to create a REST API. Sometimes, the logic is mostly in the browser and the server is just used to serve data (think backbone.js for instance). And for these projects, you don't need an MVC framework. You need something that handles a Request and returns a Response. You need a framework that implements the HTTP specification. HTTP streaming is yet another example that does not fit well with the MVC pattern.
...
And if you like to call Symfony2 an MVC framework, then you should know that Symfony2 is really about providing the tools for the Controller part, the View part, but not the Model part. It's up to you to create your model by hand or use any other tool, like an ORM.
As Symfony is a set of components, you can easily adapt your usage of the framework to the project you are working on, and the principles that you want to follow (here a REST specification).
The FOSRestBundle is very extensible.
You can define your routes manually, create different views of your objects through serialization.
Plus, I think you can keep very light controllers by writing the most of your objects management's logic inside Repository classes.
So,
Use simplified models and serialization to have different views/layers of your objects.
You should not rethink your whole Entity/Services in order to be more REST, just give them some changes/improvements in order to use them through data-transfer objects/domain objects (models) and Repository classes (fetching/storing methods).
You should be able to take benefits of use REST utilities such as FOSRestBundle, it provides more than built-in actions, allows you to make all custom stuff that you could need, be MVC or not, and be REST or not. It's at your own appreciation.
Have you considered using either Naked Objects (for the .NET platform) or Apache Isis (for the Java platform)? Both of these give you a complete Restful Objects compliant restful API for free - derived entirely from your entity models. (I am responsible for the first of these two. Our implementation is built on top of the ASP.NET WebApi framework. We have a RestfulObjectsController, with many methods on it, but these are all generic methods, corresponding to the various Restful Objects resource types - we do not need to add any new methods specific to the domain objects or their actions.

Do I need REST for a web service that requires no authenciation?

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.

CakePHP - best way to model a number of API calls

I am busy on a project that involves calling the API's of nine other sites. This number is expected to increase in the future and the actual method of API will differ (SOAP or XML).
There is a specification that each site needs to be modular so that my client will be able to sell them our API (which they can then give to other aggregators).
I've completed a number of Cake projects in the past but all of those were database driven. Can somebody advise what the best way to approach this would be?
At the moment I am thinking of making each API a plugin. I will place the API calls into a model (not attached to a database table) and then the rest will follow naturally. Because the actual views of each API will differ I won't be able to use a common controller or views (each company API we consume has different business rules).
Can anybody tell me if this approach sounds reasonable or if I'm off track?
Thanks,
Andy
Maybe in your root application you could extend AppModel. A SoapModel for Soap-based API calls and RestModel for REST-based calls, etc.
Then in each plug-in, you could make the model extend the appropriate class for the basic communication, and then you only have to handle the site-specific business rules in those models. This extra layer of abstraction would nicely hide away the WS implementation details.
You don't even necessarily need to split these into plugins if you're going the fat model route. Plugins are only particularly useful if you want to self-contain a "sub-application" of some kind and make it re-usable across other Cake applications.

Universal REST frontend - does it exist?

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.

Categories