Best practices for using Own API for client and server? - php

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.

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.

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.

Best way to call Rest API presented on the same server

I have a JSON based REST API implemented using PHP that will be called from my mobile app. I have a website deployed on the same server where the REST API existed.
What is the best way to use the existing functionality, is it by sending a cURL request to my API or just by including actual model classes source code and calling those functions?
If they're logically part of the same application, you might consider implementing the functionality of the REST API as a helper function. Then, you can include that function (and whatever model classes it needs) and get the code re-use without the overhead of creating another request.

Architecture: API as core for a website & mobile-app

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.

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.

Categories