ASP.NET Web Service POST/GET via REST unavailable? - php

I'm working with a .NET based Web Service where some of the API calls can be accessed via HTTP POST/GET but on others only SOAP 1.1/1.2 are available.
The company that has developed the API have come back to me have said the following and I was wondering if he's trying to pull the wool over my eyes or whether he's speaking the truth. His response doesn't sit comfortably with me so I thought I would try and check but haven't been able to find an answer.
I was thinking it is very odd as I
have not specified anything on the
other methods in order to make them
accessible using the HTTP Post or HTTP
Get protocols. I have globally set it
so that they should all be accessible.
I have been looking into this, and it
seems that the HTTP Post and HTTP Get
protocols can only be used with
methods that use simple types, e.g.
where a method takes and integer
parameter. The methods you have listed
below take more complex objects, e.g.
nullable type or custom objects.
However the SOAP protocol can be used
with this complex methods.

His explanation is correct. POST/GET only permits typical primitives -- int, string, bool, etc. Or rather, parameters that can be interpreted with simple name/value pairs. The SOAP protocol handles the XML side of web services in .Net (sounds like he's talking about legacy ASMX services.)
UPDATE: a little context here. It sounds like your contact doesn't know much about .Net web services, so while his description is based on what he knows, it's certainly not a limitation of the environment; he just needs to do a little more work.

He is incorrect. You can use the DataContractSerializer to send and GET complex types.
Here is some code I used to answer another question recently:
In order to POST parameters, you need to serialize it using the DataContractSerializer. e.g,
On server:
[OperationContract]
[WebInvoke(Method="POST",UriTemplate = "/foos")]
void PostFoo(Foo foo) {}
On client:
var foo = new Foo();
var content = HttpContentExtensions.CreateDataContract<Foo>(foo);
var client = new HttpClient("http://example.org/service.svc/foos");
client.Post(content)
The client code uses the Microsoft.Http library that is found in the WCF Rest Starter kit.

Related

PHP Architecture: Save and use "constants" in whole system

I use my PHP (like normal) in a server architecture where I have an incoming request and build an outgoing response. All request attributes (like client ID) are given to each sub function and class to make magic with (like in my Mappers and Models and Helpers).
Is there an idea to work with request data WITHOUT putting it from function to function to function.
Idea 1: Make my Request/Response object static. I have exactly one request and one response so there is no problem to do this.
Idea 2: Saving data in Session (or similar). This also sounds uncomfortable and heavy.
Is there another idea doing this?
Implement your own Request or RequestContext class and populate a object of this type with all the data that ongoing methods might need. This way you don't need a growing number of arguments for each of your functions, instead you just forward the entire Request.
This is much easier to extend and you don't suffer drawbacks of "global" data. It's a typical pattern which is used by a lot of frameworks as well.

Abstraction of external service / API request and response

TLDR: Writing a service (in the model layer). It talks to ffmpeg. Where should validation go? Should I create a service response object so it is testable? How should it be structured?
Background: I'm designing some classes to retrieve data from an external service. It could be an API, but in fact it's calls to ffmpeg cli, which in effect is an API to the conversion tools themselves.
When talking to an external service, where the data retrieved may not always be the same, how is it best to go about maintaining at least a consistent application state on your end so your application doesn't depend on the external service to work?
I have already separated out the classes thus far, trying to maintain SRP within them:
class CommandDispatcher { }
The Command Dispatcher's sole job is to make a request for data (to ffmpeg) and retrieve the response for that data back.
class Converter { }
The converter's sole responsibility is to take user requests (like convert 1 to 2), and send the basics to the command dispatcher which handles the exec() calls.
Here are my questions:
When talking to an external API / service, should I be creating an APIRequest and an APIResponse object (in this case an FFmpegResponse object)?
I have seen examples of this for OAuth, where there is an OAuth response object. However, that's simple enough because calls to this are done over the HTTP protocol which tends to give back at minimum an error code and a message. Calls to something like ffmpeg don't guarantee a similar response (ffmpeg may not be installed, for example). Is this object merely a domain object (i.e. an entity: some class members and setters and getters)?
Validation. If I am creating an FFmpegResponse object, whose job is it to put the data into the right members of the Response object?
Imagine ffmpeg isn't installed and the CommandDispatcher gets the response back empty. Is it up to the CommandDispatcher to then populate the FFmpegResponse object with an "ffmpeg not installed" error? Should I have a validation object do this?
Remember, I'm trying to stick to the Single Responsibility Principle here, so I'm thinking that the CommandDispatcher shouldn't care about whether the data is valid or not - it should merely ask for data and retrieve it. Where does my validation fit within the model layer for this service?
This isn't only for FFmpeg but will help for future external service calls. What is the best [practice] way to structure your code and classes to maintain SRP yet also a consistent application state regardless of whether or not the external service responds in an expected way?
In your current structure, CommandDispatcher should be either an interface or an abstract class (depending on the necessity of abstract code). You would then create a concrete implementation: FFMpegCommandDispatcher which would encapsulate the understanding of ffmpeg specific responses.
Response objects will then take on a similar structure: CommandResponse would be an abstraction with the concrete implementation FFMpegCommandResponse.
It would be best to create a set of common error conditions (serviceNotAvailable, serviceNotInstalled, serviceDiedAHorribleAndBloodyDeath, etc). Your dispatcher implementation can then set a common error code on the response object and provider implementation specific details. ('Error 1984: FFMpeg is watching you')
If you're concerned (and I would be) about validating input as well. You could create a CommandRequest abstraction, and FFMpegRequest implementation, that will take user input and make sure that it's okay to be sent to the command line.

A Backbone UI and a CMS backend: Wading through the Restful CRUD

Backbone tutorials I have read implement some type of a mini-framework (i.e. Slim) with a RESTful architecture performing CRUD on a server db, like this. The Backbone docs state you need a RESTful api, which I believe is due to the Backbone Route and Sync functionality that keeps models up to date, which is a huge aspect of my choosing to use Backbone.
For example, the line below maps a faux url (route) to the 'addWine' function (within a Slim api):
$app->post('/wines', 'addWine');
Assumption 1: If I have a (PHP) CMS backend (and not a mini-framework) I assume I could simply replace the 2nd parameter (addWine) with my own CMS class method call and return a json object.
Assumption 2 But I would not be able to directly call that same class method from a link in the html without causing backbone to lose state and thus it's ability to sync the model data (and remember the browsers history).
Assumption 3 In that case, I will need to use the Slim api and route backbone urls through (Slim) RESTful CRUD calls in order to access my CMS database to keep backbone happy.
If those assumptions are correct, then it would seem backbone is intercepting those HTTP calls - which leaves me wondering how the whole RESTful + Backbone relationship works. Can you explain some of it?
If my assumptions are incorrect, then I need more help than I thought. Can you help with that?
Thanks
I can't speak intimately to your three assumptions, but as for your final question -- Backbone does not "intercept" HTTP calls -- it constructs them, just as any other javascript library would to create an AJAX request.
Backbone is relatively agnostic to your server side language/framework. Here is what Backbone expects any time "sync" is called:
Backbone's sync function uses different HTTP request types based on which method was called. These different HTTP request types are:
POST
GET
PUT
DELETE
Your framework needs to support all of the above to support the "out of the box" functionality of Backbone. This means that you must specify all of the above routes within your application in order to work with Backbone.
One other thing to note is the "create" and "update" method does not carry post data with the request specifically -- instead it sends a content body with a json digest of the data and expects the server side to properly parse a JSON object and deal with it appropriately.
I say yes to all three assumptions and also agree with #Andy Baird.
Also, the only problem to your project is how to notify Backbone that you have updated the database and you would like it to update itself in the front-end. I can only see two solutions:
1) using Javascript's setInterval() - if you do not need the front end to be updated immediately on DB update, you can check for changes every 1 minute, Backbone knows to only update what has changed and add new stuff but of course this is not healthy to the server if you have 1k active people making repeated request every minute
2) using SocketIO or similar service - this way you can send from the server to Backbone either the entire list of modifications to your DB or a simple 'Please refresh, new stuff waiting'. Check this discussion.

How to deal with the 'DataSet' data structure in php?

I'm trying to do a call to a soap webservice from php.
The webservice returns an ADO.NET DataSet structure. Are there any libraries in PHP that can deal with this sort of data structures? If so, what are they called and where can I find them? If not, feel free to give tips?
So far, I have this (using ActiveMQ and the NuSoap library):
/**
* Create a new service instance
* Provide ActiveMQ uri and the extended class name
**/
$client = new Client('tcp://localhost:61613?tcpNoDelay=false', 'test');
/**
* New service reference
**/
$service = new ServiceProxy($client, 'ServiceName');
/* Service call */
$result = $service->get_clients();
get_clients() is a method that does the actual service call and it gets the DataSet structure in return. How can I manipulate this return value?
In .NET for example, there is a DataSet class. The ADO.NET DataSet contains one or more ADO.NET DataTables which in their turn consist out of one or more ADO.NET DataColumns and DataRows which are returned in a collection (array).
A simple code example, where the DataSet only contains one DataTable, can be:
/**
* Here, the val variable will contain the data positioned in the
* first field of the first DataRow of the first DataTable
**/
string val = dataset.Table[0].Rows[0].ItemArray[0];
I want to do the same in PHP, but I need a helping hand.
I would suggest you try learning more about the structure of the data you are working with. It is most likely some form of JSON or XML, which can be manipulated through the large set of PHP xml and json handling libraries.
Your first step is to look at the data being returned by your request and identifying it's format. Microsoft documents the ADO.NET API's datasets in depth HERE at the MSDN library. This should help you to make sense of what you are seeing when you inspect the data. Some data providers allow you to access the same data in different formats, depending on a parameter or a family of similar functions. Do you have documentation for your providers API?
Next, after you have identified the format and deciphered the specifics of the datasets schema, You need a class to manipulate the data. If you are dealing with something that conforms to a published standard you can use something like simpleXML, JSON or DOMXPath.This class should store the data in protected member variables and provide methods to inspect, iterate, load, refresh, search and so forth. You should refer to the PHP manual's function reference for help here and write whatever functions you need. I would write it generically to handle any similar dataset and derive a class to expose exactly the data I need for a particular application.
Another approach would be to write a COM component in a .net language to access and manipulate the data and import it's functions through PHP's COM extension. I think I would go with this choice if the data format is a weird proprietary Microsofty one.
The third possible approach works only if you have programming access to the server. If you can adapt the service provider to comply with the specification, Microsoft has released an interoperability toolkit which is supposed to act as a bridge between .net services and PHP clients using a layer of proxy objects to expose the ado.net data to PHP scripts. They throw the word RESTful around alot, but I'm not really sure what they mean by that. Check out the OData SDK for PHP HERE at Microsoft's interoperability HQ (there is info here about PHP and other Microsoft platforms and products like Azure, silverlight, Bing, etc., as well). As I said though, I think you would need the data provider to emit data which conforms to their standard. Perhaps it already does. I can't tell without a schema! If so then this is your best bet.
Good Luck!

How to create a RESTful API?

Over the last few weeks I've been learning about iOS development, which has naturally led me into the world of APIs. Now, searching around on the Internet, I've come to the conclusion that using the REST architecture is very much recommended, due to its supposed simplicity and ease of implementation.
However, I'm really struggling with the implementation side of REST. I understand the concept; using HTTP methods as verbs to describe the action of a request and responding with suitable response codes, and so on. It's just, I don't understand how to code it.
I don't get how I map a URI to an object. I understand that a GET request for domain.com/api/user/address?user_id=999 would return the address of user 999 - but I don't understand where or how that mapping from /user/address to some method that queries a database has taken place.
Is this all coded in one PHP script? Would I just have a method that grabs the URI like so:
$array = explode("/", ltrim(rtrim($_SERVER['REQUEST_URI'], "/"), "/"))
And then cycle through that array, first I would have a request for a "user", so the PHP script would direct my request to the user object and then invoke the address method. Is that what actually happens?
The main thing I'm not getting is how that URI /user/address?id=999 somehow is broken down and executed - does it actually resolve to code?
class user(id) {
address() {
//get user address
}
}
Actually the API you're trying to describe now is not RESTful. There are many sources describing how to make RESTful APIs. So you should first define your API (taking in account how your client software would use it) and then implement it. I'm quite sure that almost any RESTful API can be implemented in PHP.
Here are some other tips on how to make a RESTful API.
In my opinion GlassFish Server REST Interface is a good example of RESTful design.
That's two questions.
To honor RESTful HTTP verbs, you have to query $_SERVER["REQUEST_METHOD"]. It will contain the usual GET or POST unless a more specialized HTTP request was received. The whole REST buzz is somewhat misleading in itself, and also in misusing the HTTP verbs just for routing.
Anyway, the mapping of request URLs to functions can be achieved in two ways. It's most reliable to use a static map, for example an array that lists URL patterns and destination methods. Most PHP frameworks use an implicit mapping like so:
$args = explode("/", trim($_SERVER['REQUEST_URI'], "/"));
$class = array_shift($args);
$method = array_shift($args);
call_user_func_array("$class::$method", $args);
Note how this is a bad example, security-wise. Only allowed and specifically prepared classes and methods should be able to receive requests. Most frameworks just check if it was derived from an acceptable base class after loading it from a known path and/or instantiating. But a static map is really preferable.
Anyway, regular expression mapping or handling by mod_rewrite is also common. And for utilizing HTTP verbs, just include it as method name.
Have a look at FRAPI - http://getfrapi.com/
As it says focus on your business logic, not presentation.

Categories