How to invoke webservice defined in grails application from php - php

I am newbie to webservices
I have a domain class as below in my app.
class Training{
string name
Date date
}
and i want to display the list of training in php page
What changes i have to make in grails and in php script to do this.I want the data in JSON format.
And I want to follow the RESTful architecture.
Basically I want to interact with grails app from my website (written in php). In future i want to do save the data from my website to grails app DB and many calls.
And Do i need to authenticate before serving the request in webservice.

If you want to follow the architectural pattern see following link: http://grails.org/doc/latest/guide/webServices.html#REST
First create you TrainingController controller which performs the requested action and returns the json data. e.g.
class TrainingController {
def show = {
render Training.get(params.long('id')) as json
}
}
if you don't use a special url mapping to match the restful pattern, you can simply call training/1 and get the json structure returned. See the documentation for more rendering options.

Related

REST api - Updating table with POST from view

I'm new to RESTful web services and still figuring out the design/architecture aspect coupled with MVC pattern. I am using Codeigniter framework to implement MVC.
I had a pretty simple question. I am using using form data to update a table in my database. I have written an api that will do this:
http://www.example.com/api/resource/tablename/?param1=info1...
Typical api. What I wanted to know was, in the MVC pattern should I be using cURL in my VIEW to POST data and update my table with the form data or should I still be send the POST data to my controller and make the api call from the controller to update the table.
To me it seems arbitrary at this point as both will accomplish the same thing but what is the standard practice? Is it okay to directly communicate with you api from the VIEW to update your db table??
Is it okay to directly communicate with you api from the VIEW to
update your db table??
Yes, it is...in fact that is pretty much what you should do in this case! Send your data directly to the API. Your API should do all data validation and return an error message (in a standardized format like JSON, XML etc) if any data validation fails OR perform whatever action it needs to do with the POSTed data. A great benefit in doing so would be that your API can be used by any caller and would be a complete ecosystem by itself.
Without knowing more about your intended applications I can say this:
Typically you want to try and keep any processing logic (PHP) out of your views if possible. The whole point of the controller is to handle transaction operations from your model and then pass it to your view. So if you are using an API to gather some data from a service that is intended to be used/manipulated in your view then the logical location for that would be in the controller.
The MVC pattern isn't a hard and fast law of X goes in Y and Y goes in Z. It is a pattern that makes it easy to extend and abstract your data gathering, processing logic, and visual layouts.
Technically depending on the application and how you planned to use it you could create a model for the API so that it could be used in multiple controllers without the need to re-write it.

How to structure a website built upon own API in laravel

I'm building a small TV Show library in laravel. I want to include an API as well for possible future expansion. When I started I had 2 controllers for what should have been a single controller: API controller and the web frontend controller. They both handled the same logic. That's obviously not good practice since that leads to duplicate code.
How would I make my application API centric? I was thinking of having an API controller which handles all the logic and returns a JSON object and a regular controller for the frontend which simply takes the JSON object returned by the API controller and passes it to a view (after, if any, processing). If that's the way to go, how would I retrieve said object? A GET request to my own server?
If you are developing API, than it should be on a separate server to take off load form main web server.
If it is on a same server, why would you send a request to it as you can develop a class that can act as API and call it inside your web controllers.
Later on when you decide to have separate server, just wrap API contoller around that class.
<?php
$myApi = new MyApi();
$myApi->setParmas( $paramsArray );
$myApi->doLogic();
echo $myApi->asJson();
// or make API class that can handle one liner
echo MyApi::factory($_GET)->doLogic()->toJson();
?>
Make your Laravel application an API endpoint and use a frontend framework or some frontend routing and templating libraries to handle the client-side.
Name space the api with /api and versions i.e. /api/v1
This allows you to easily develop with many different technologies and not have to rewrite your backend, as it is just an API endpoint.
It can then serve your webapp, an iOS app, an Android app, etc. because all it does is handle data, validation, requests, security, etc.
You can use repositories to get required data, then you may pass it to a View to make a webpage, or just print the JSON, for the API, this way you can prevent duplicate code.
Route::get('/latest', function () {
return View::make('latest', Movie::latest());
}
Route::get('/api/latest', function () {
return json_encode(Movie::latest());
}
Check this video for more info about repositories in Laravel: http://vimeo.com/53029232
In larval 5.3 you may want to consider using larval passport which provides a really nice way to consume your own api's from the front end without needing to worry too much about the authentication https://laravel.com/docs/5.3/passport#consuming-your-api-with-javascript
There is also a nice video on this on laracasts https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/13

Is it advisable to use API based architecture for both native and non-native sites?

I am planning to use a architecture (MVC = PHP->Yii) where I will be using REST API based architecture for native site (main web app) and non-native (apps such as iPhone, BB, WAP etc).
No my question is it advisable to use View-Controller (HTML+User Requests) (For Main Site) with Controller-Model (Request/Response+DB) (for API) and same API platform will be used for non-native apps, or should I use full MVC for main site and build separate platform for APIs. This is because I don't want additional HTTP (cURL) overhead for main site.
Update:
#karmakaze
That's the though with me but still I have to write RestControllers because there is lots of code involved. So anyway we ends up having two different controllers e.g.
UserController extends CController {
actionRegister() {
...Some calculations
.
.
Instead of making Calls to model We will use call controller i.e.
$userRest = new UserRestController();
/*
* This will return json data or php obj depending on params passed or
* may raise an exception
*/
$userRest->actionCreate($param1, $param2);
// Process data obtained.
}
}
or is there any other way around?
If it fits your needs, you may build a front-end based on some JavaScript libraries like AngularJs, BackBone.JS or any other MVC JavaScript library.
This way you should build only one RESTful API in Yii, as the back-end of your app.
This solution, however, lets something uncovered: it will be hard to make the application crawlable.
The perspective of the question made me to understand that it is relatively important to render the HTML on the server side. I am thinking at this solution:
make normal MVC app, including controllers and views
Use any of the following ticks:
a GET parameter that will be false by default, but ture when it is an API call:
Check this example:
// in a controller:
public function actionView($id, $api=false) {
// some calculations, getting the $model variable
if ($api) {
echo $model->json_output(); // you can implement it in components/model.php or generate the json output some other way
} else {
render('view', array('model'=>$model));
}
}
a subdomain called, for instance, api (you'll have api.yourapp.tld),
or use another HTTP parameter from the request to determine if it is an API call or not.
Any of these version will bring a way of verifying if the client requests a JSON/XML response (API call) or HTML for the browser.
This way you avoid the headache of building separate controllers for the API and the main site.
Note It is not required to do this trick for actions when they simply render a form - it is useless.
Note 2 You can use the latter method to render the requests with _request_fragment and assume that every request is an API call unless $_GET['_request_fragment'] is specified. Like this you can make an AngularJs, Blackbone.js app crawlable with Yii.
UPDATE The _request_fragment is specified here, and it is used by most search engines to crawl AJAX web applications.
You can use the same for both native and non-native app, it will also reduce you work at development time as well update or change ur logic.... I do have so many experience with such situation..
Use full MVC for main web app and reuse the same Models and Controllers to build the REST API. There are extensions which will do this automagically if you follow Yii conventions while building the main web app. Just search REST in the Yii extensions. We'll be doing the same for our mobile apps. Currently investigating RESTFullYii.

RESTful API design pattern while creating API with php

I am developing RESTful with php. Currently I have started coding with MVC design pattern. In which the view files are acting as an interface. An interface which isn't showing any graphical UI but it has all the request handling logic.
Now, my question is the way I am coding is correct or there is a better way to create RESTful api in php?
My inspiration is based on JavaEE application model. In which we have Entity classes as model, Java beans as controllers and Remote Interface is the the list of method which gets called from client (kind of a view).
Am I on right track?
A good example for building a RESTful API in a PHP based MVC framework can be found at http://www.chrisdanielson.com/2009/09/02/creating-a-php-rest-api-using-the-zend-framework/.
This example extends a class in Zend Framework called the Zend_Rest_Controller which simplifies this process. You can have a look at the source code to see how they do it and if it gives you an ideas on how to make your own implementation.
To answer your question though, you should have controllers acting as the interface. So if you send a POST request to myapp.com/comment (where comment is the controller), it knows you are trying to add a new comment. If you send a GET request to the same URL, it knows you want all of the comments, and if you send a GET request to myapp.com/comment/4 it knows you want to get the comment with ID 4. Your views should have nothing to do with the internal functionality of your API.
You can use any existing RESTful PHP MVC framework, like Yii or Kohana both are very light and natively support RESTful applications.
For your existing application, MVC model states that all the requests and logic handling should be done by the Controllers not the views. Things are usually done in one of two ways here:
(1) Controller has a special method to respond to each type of requests and acts differently As seen in RubyOnRails (mainly at the end of each controller action)
respond_to do |format|
format.html
format.xml { render :xml => #events}
format.json { render :json => #events}
end
(2) Controller detects the current requested format and changes that entire theme/layout to, say, a JSON theme (All layouts/views receive the same data). This is my current implementation and it goes like:
$format is any of [html,json,xml] (detected from url suffix)
$controller->layout = "$format";
$controller->render($viewFile, $object);
view file in HTML Layout
<div id='model>
<h1><?=$object->title?></h1>
<p><?=$object->description?></p>
</div>
View file in JSON layout
echo json_encode($object);
View file in XML layout
/** Loop and build XML tree */
I did a bunch of webinars on API Facade Design Patterns. Hope you will find the concepts useful irrespective of the underlying technology you use to implement it. Please can find it here
http://youtu.be/n8B-K3iJ7b4
http://youtu.be/MRxTP-rQ-S8
http://youtu.be/aJBhVm4BbCI
Apigility is a Zend Framework 2 based project designed soley for the purpose of creating REST and RPC services.
https://apigility.org/
Out of the box you're given an easy way to get started with MySQL and OAuth2 for authentication.

Correct code structure when providing REST API access using Zend_Rest_Controller

I'm new to Zend Frameworks and MVC type programming (not PHP though) and I'm trying to provide API access to data on my server using the Zend Framework.
I'm using Chris Danielson's article (http://www.chrisdanielson.com/2009/09/02/creating-a-php-rest-api-using-the-zend-framework/) as a base.
I want to provide access to data in the following formats:
(a) http://www.example.com/api/createevent
Data will be POSTed here, success will return an id, otherwise an
error message/code
(b) http://www.example.com/api/geteventdetails/1234
GET request will return data
(c) http://www.example.com/api/getregistrationdetails/1234
GET request will return data
(d) http://www.example.com/api/getregistrationdetails/1234/567
GET request will return data
Questions:
There is a default file which is located at \api\application\controllers\VersionController.php which enables handling of URLs of type: http://www.example.com/api/version . Should I be creating a separate file located at: \api\application\controllers\GeteventdetailsController.php which handles requests of type (b) (and one for every type of request)? If not, where should I be placing my code to handle these multiple request types?
How can I get the parameters passed in (b) to (d)?
To do requests (b) to (d), I need to fetch information from my server's database. Where should I place the code that does the actual MySQL query?
I have used routes a lot in ZF, but not the Rest implementation, having swatted up on the docs and on the tutorial you linked to - I will do my best to help you...
It might be worth looking at the docs for the Rest router (about 1/3 down the page) - it explains that it will automatically create routes for you based on the method of the request; so your naming format of createevent, geteventdetails, etc shouldn't be needed.
Question 1.
Rather than creating the file
\api\application\controllers\GeteventdetailsController.php
I'd create the file
\api\application\controllers\EventsController.php
This will be one controller to handle all the event actions, be that getting, posting, putting, etc. Your suggestion is too specific for the controller as the get, put, etc will be handled at the action level.
Question 2.
The routes described in the docs show you that the final parameter (:id) will be assigned to a parameter in the controller called id.
So accessing the URL /events/ using GET will invoke the indexAction() in your EventsController.php file
And accessing the URL /events/99/ using GET will invoke the getAction() in your EventsController.php file. You can access this id from the controller like this
$id = $this->getRequest()->getParam("id");
OR
$id = $this->getRequest()->id;
You should then write code to query the database for a listing of events or for a specific id. Which brings us nicely on to...
Question 3.
Rather than putting the code for querying the database for events into the controller you should create models for your database tables and rows. I'd recommend using the existing setup in ZF for Zend_Db_Row and Zend_Tb_Table to do this. This will ensure your application/website is MVC.
Putting the code inside the contrller may hinder development later, for example when you write a registation form for an event at a later date in another controller. The logic for creating the event will be duplicated, once in the new controller and once in the Rest controller. You'd be better off centralising this logic into a model for manipulating and querying events.
I hope that helps!

Categories