I am trying to understand what exactly a REST-based API is. From what I understand it is just a convention for writing the functions within the API? All functions should be of either GET/POST/DELETE/PUT form? So, for example a function in a REST API could be
public string getLastName(User x)
{
return x.lastName;
}
I am mainly confused about how JSON/XML play a role in this?
Its more than just a convention. The concept behind a REST API is that you access it using the HTTP verbs, and that the functions those verbs have been mapped to perform the described action.
For example:
GET will return data to the caller/sender
DELETE will delete a record
And it goes further, but a lot of it is based on relying on HTTP to provide a level of consistency. For example, in a RESTful service, you might use the Accept HTTP header to request a JSON response or an XML response by supplying the application/json or application/xml values, respectively. This is just a simple example, and it is up to the implementer to decide how their API will work, but it highlights the importance placed on leveraging HTTP.
Why JSON/XML?
Along the same lines, JSON and XML are used because they are widespread and standard ways of representing and transmitting data over the web. JSON (JavaScript Object Notation) is very common in doing data transfer (especially on GET requests) due to most requests coming from JavaScript, and JS can easily interact with JSON without having to do the parsing required when dealing with XML. On the other hand, XML provides its own benefits, such as the ability to use schemas and namespaces. You may already be aware of benefits/drawbacks of each, but that's a separate discussion. The main point is that JSON/XML are the primary ways of communicating data in a REST API due to both of them being the de facto standards of the web.
There are lots of good resources for more information, this MSDN article may be helpful: http://msdn.microsoft.com/en-us/library/dd203052.aspx
There's a lot of confusion and misconceptions around REST. Unfortunately, it's a lot more common to find applications that are doing the exact opposite of what REST means and calling themselves RESTful than real REST applications.
From what I understand it is just a convention for writing the functions within the API?
No, REST is not just a convention for writing functions within the API, nor it's directly related to SOAP or HTTP as other answers here say. REST is a software architectural style inspired by the successful design decisions made for the web itself. To put it in simple terms, a REST API should work like a website does.
When you enter a website, you go to a homepage having an idea what the website is about, and the HTML document will have hyperlinks pointing you to the resources you need. The only out-of-band information are the media-types of the resources themselves, not how to find them. For instance, when you enter StackOverflow, you know what questions and answers are, and you look for links pointing you to them. How your browser render those links, how you choose them and follow them isn't different from other websites, like an email or news website. What makes it different is the media-type of the resources you're after.
That's how a REST API should work. Clients should not depend on any out-of-band information other than detailing what the resources do. They should connect to a home page that returns them links they should follow to do whatever they need. If an API doesn't do this, then it's not REST. Period.
I like to call those APIs "street-REST", because people often implement them by copying what they see in other APIs that also call themselves REST, and by what other people talk about REST.
All functions should be of either GET/POST/DELETE/PUT form?
That's a common confusion, and you'll see a lot of that, including people conflating that to CRUD operations, or that REST doesn't allow any other verbs, etc. That's bull.
REST is independent of any particular protocol, so it doesn't make sense to say functions should follow HTTP methods. REST constrain your applications into an uniform interface, meaning that whatever protocol you should using, you must stick to the standardized behavior as much as possible. If you're implementating a REST application over HTTP, this means your API must stick to the HTTP methods for the client-server interaction, meaning you can't invent other HTTP methods as some applications using HTTP do. If you change the communication protocol, clients need to know that information before entering your API, and that's more out-of-band information.
How you implement this on your code is irrelevant to REST. REST isn't a development pattern or philosophy, but an architectural style.
I am mainly confused about how JSON/XML play a role in this?
There's a lot of confusion on this too. On a REST application you should define abstract entities with states describing all the behavior you need. The API will serve as a channel to transfer media-type representations of those entities between client and server. REST means Representational State Transfer. The URI the client is requesting is an identifier for that resource, and the metadata for that request will tell the server what media-types the client is prepared to accept. JSON/XML don't play any direct role in REST, at all. They are simply one representation media-type that is easier for computers to parse and obtain information, in contrast to formats like text/html, which is meant to be rendered for human visualization by a browser.
For example, take StackOverflow itself. What's a question, in the abstract sense? It's a request for information. How that abstract resource is formally defined? There's an author, there's the actual text of the question being asked, there's the upvotes and downvotes, the comments and possible answers, etc, all of which are also abstract resources with their own definitions. The actual data is stored in a database somewhere, and when you request your homepage, it returns links with URIs identifying those questions. Take this question for instance, it has the URI http://stackoverflow.com/questions/24092517. When I want to read that question in a pretty document rendered on my browser, I will request that URI, but telling the server through the Accept header that I want a text/html representation, and my browser knows how to render the HTML into a pretty page. On the other hand, when I want to request that question to store it back on a database, for instance, I don't need all the cute stuff needed to render a pretty document page, so I ask a format that's easier to parse and doesn't contain a lot of unnecessary information, like JSON or XML.
Most people who build street-REST APIs understand this point, but they miss the most interesting part, which is that you're not limited to media-types that already exist. You can create private media-types that only exist within your API, or your company's ecosystem of applications. So, for instance, instead of calling the media type of all JSON documents application/json, no matter the content of them, we could have custom media-types that reflect more accurately that particular type of resource. So, we could have a application/vnd.stackoverflow.question.v1+json for StackOverflow questions represented in a JSON format. Once you do that, instead of wasting time documenting operations already standardized by the communication protocol, you should focus on documenting that custom media-type and how to interact with it, independently of the communication protocol. Once you have that clear, clients can interact with your services using any protocol available.
If you understand these three main points, you understand what REST is about. By using hyperlinks as the engine of your application state you're not tied to any particular point in time of your implementation. Your server can evolve at will, you can change URIs as much as you want, and clients won't break. By sticking to the standardized protocol, it's easier for generic clients to make use of your API, not to mention that it's easier for developers to understand how to integrate if they already know that you won't break the protocol. By focusing your design and documentation efforts on your media-types, not on protocol details and URI semantics, you're avoiding introducing more out-of-band information needed to drive your API, and your clients are also more resilient to changes.
REST API's act as middleman to deliver data packets between the web service and an application wanted to use some resource from web service for its operations, in order to do so Json comes into play, which helps in data transfer/communication over the channel. When one's application wishes to get list of resource, it actually get complex data or queryset from database which turn into simple data type with serialization and then turn into json to travers the channel.
RESTful API is much more than just the convention of writing functions.
The abbreviation REST stands for "REpresentational State Transfer".
REST APIs are used to call resources and allow the software to communicate based on standardized principles, properties, and constraints. REST APIs operate on a simple request/response system. You can send a request using these HTTP methods:
GET
POST
PUT
PATCH
DELETE
Also, REST APIs can include endpoints, headers, URL parameters, and the request body.
The endpoint (or route) is the URL you request for. The path determines the resource you’re requesting for. Think of it like an automated answering machine that asks you to press 1 for service, press 2 for another service, 3 for yet another service, and so on.
I am mainly confused about how JSON/XML play a role in this?
When you send a request to an endpoint, it responds with the relevant data, which is generally formatted as JSON, XML, plain text, images, HTML, and more.
I am mainly confused about how JSON/XML play a role in this?
JSON/XML are called streaming data format. There are others but over the years these two became so popular because of low latency they provide. XML is probably still little bit more popular than JSON, but JSON is more compact.
Also another main reason to use them is because they are both supported by almost all languages and their frameworks.
Related
First off a little context, I work for a channel manager company that builds custom endpoints for their clients to talk to. We currently mostly code in c#.
This is the first time we are connecting with a client that asked us to support a soap web service.
Sadly, we don't have previous experience in this and I can't find any concrete explanations to what it looks like to support a SOAP call.
Currently, it looks like that I have to simply use text processing methods to run through the received XML and parse it in a non-generic way.
But this feels like there should be a more straightforward approach since the protocol is almost 20 years old.
For almost every search result I only get examples of what the XML looks like, but what I'm interested in, is what I need to implement in my application to host an endpoint for the client to successfully post and receive a SOAP message from. And if there is a way to do this without something like XmlWriters/Readers.
Anything to help me get on my way mary is appreciated!
Greetings, Davey
WCF is the least outdated library for offering SOAP.
When you can define the contracts then you're in luck, that's just writing a C# interface.
But when necessary you can also import WSDL specifications and generate C# from that.
it looks like that I have to simply use text processing methods to run through the received XML and parse it
Don't even consider that. Everything is under control of schemas. And you will also have to generate valid return packages.
I have APIs from around 6 providers. I also have a database where I disable or enable the providers I want to use.
I have an ASP.NET MVC4 application. In this I want to be able to use multiple provider's APIs and display data. Each provider's API send a response in a different format - it could be JSON for one and XML for another.
Now I am stuck because:
Each API needs its own code to be parsed. Where does this provider-specific code go into? A single class where for each provider a specific method does the parsing? Or do I create a new class for each provider and do the parsing there?
How can I efficiently call a particular provider's method? Is some bit of hardcoding essential in the sense that if the Provider name is "Prov A" then I call the method GetProvAData?
I hope I have explained the issue clearly enough. Any help will be welcome. Thanks in advance.
Regards,
Satish
This really has nothing to do with MVC, it's a basic software development pattern problem.
Assuming your data from various providers all has to end up in the same format, then this is a textboox example of the Strategy pattern. You would basically create multiple provider parsers that all have the same interface, and you just call Execute or Parse or whatever you want to call it on all of them.
If what you do with the data is different for different providers, then it's a bit more complex because you now have to modify your app to support the individual providers data, and without knowing exactly what that is we can't really give you advice on how to do it.
Let's say you have an ASP.NET MVC 4 Web API project. One of your resources, when you call it by URL, waits while it gets performance monitoring data for a specified amount of time and then returns it all in JSON form once it has completed. However, between entering the URL and when the process has completed, is there a way to return data dynamically, ie. at each second when performance data is retrieved and display it in the browser.
Here's the issue:
Calling an API resource via URL is static as far as I know and as far as anyone seems to know. Meaning, the JSON won't appear until the resource has retrieved all of its information, which is not what I want. I want to be able to constantly update the JSON in the browser WHILE the API resource is retrieving data.
Since I'm working in a repository class and a controller class, Javascript is not an option. I've tried using SignalR, but apparently that does not work in this scenario, especially since I'm not able to use Javascript.
Is there any possible way to get real-time data with a URL call to the API?
Case in point:
Google Maps.
The only way you can call the Google Maps API via URL is if you want a "static" map, that displays a single image of a specific location. No interaction of any kind. If you want a dynamic, "real time" map, you need to build a web application and consume the API resource in your application with Javascript in a view page. There is no way to call it via URL.
You can put together an old-school ASP.Net IHttpHandler implementation regardless of MVC controllers and routing pipeleline. http://support.microsoft.com/kb/308001. You would then have full acesss to the response stream and you could buffer or not as you see fit. You've got to consider though whether you want to tie up worker thread for that long and if you're planning on streaming more or less continuously then you definately want to use IAsyncHttpHandler while you await further responses from your repo.
Having said that, Web API supports Async too but it's a little more sophisticated. If you plan on sending back data as-and-when, then I'd strongly recommend you take another look at SignalR which does all this out of the box if you are planning on having some JavaScript client side eventually. It's much, much easier.
If you really want to write Async stuff in Web API though, here's a couple of resources that may help you;
http://blogs.msdn.com/b/henrikn/archive/2012/02/24/async-actions-in-asp-net-web-api.aspx
And this one looks like exactly what you need;
http://blogs.msdn.com/b/henrikn/archive/2012/04/23/using-cookies-with-asp-net-web-api.aspx
In order to use that PushStreamContent() class in the example though, you'll not find that in your System.Net.Http.dll, you'll need to go get that from the Web API stack nightly builds at http://aspnetwebstack.codeplex.com/SourceControl/list/changesets
YMMV - good luck!
I think what you're asking for is a sort of streaming mechanism over HTTP. Of course doing that would require sending a response of unknown content length.
This question deals with that sort of chunked transfer encoding which is probably part of the solution. Not knowing what is on the client side, I can't say how it would deal with the JSON you want to push through.
Great question.
You can certainly start streaming the response back to the browser as soon as you want. It's normally buffered, but it doesn't have to be. I've used this trick in the past. In fact SignalR does something similar in some operational modes, although I should add (now I've re-read your question) that although HTTP supports this, it won't be obvious by default from a Web API controller. I think you'll need to get a little lower into the response handling so you can flush the buffer than simply returning a POCO from your web method if that's what you mean.
Essentially, you'll be wanting to write and flush the buffer after you've gathered each piece of information, so I don't think you'll be able to do that with the typical model. I think you'll need a custom message handler http://www.asp.net/web-api/overview/working-with-http/http-message-handlers to get at the payload in order to do that.
I'm curious though, you say you want to send back JSON but you're not allowed JavaScript?
I have an Linq Expression and I want to convert it to a querystring for REST, i.e.
public IQueryable<Organisation> Organisations;
...
var organisations = Organisations.Where(x => x.Name == "Bob");
becomes
http://restservice.com/Organisations?$filter=Name eq "Bob"
I did find one eventually in Linq2Rest (also a NuGet) which seems to fit the bill. Doesn't support OAuth but would be possible to build this in.
If you are control over the datasource, it's OData what you are looking for.
A google-searched brought HttpEntityClient up, although I don't have any experience with it but it looks useful.
I guess you could also write your own implementation, because frankly, rest-apis don't have to follow a certain standard when it comes to filtering, ordering etc...
PocoHttp can do exactly what you want. Moreover, it can do the call to the service and deserialize entities for you.
You can also easily modify its ODataProvider to support additional OData native functions (length, startswith, etc.)
Early pre-release versions of the OData Library had a query string parser, but expression building was never fully implemented, and the feature was then dropped. It's major hole in the library, since without it, you are left with payload and some header support only.
Fortunately Linq2Rest does exactly what you need, with one line of code:
var organisations = Organisations.sources.Filter(Request.Params).OfType<Organisations>()
The cast is necessary because a query string can select against the collection, producing a different collection of types. If you are only predicating on properties, then you don't care about that.
I found that DataServiceContext developed by Microsoft works much smoother than Linq2Rest and HttpEntityClient third party libraries mentioned here.
Documentation is also much better. The downside is that DataServiceContext works with XML only (no JSON).
But both WebAPI OData REST services and WCF Data Services can return XML, if it requested by a client in HTTP header. Because XML support takes no additional development work, lack of JSON support is unlikely to be an issue.
There are LINQ to REST examples using DataServiceContext: http://msdn.microsoft.com/en-us/library/windowsazure/dd894039.aspx
try Odata
The Open Data Protocol (OData) is a Web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from a variety of applications, services, and stores. The protocol emerged from experiences implementing AtomPub clients and servers in a variety of products over the past several years. OData is being used to expose and access information from a variety of sources including, but not limited to, relational databases, file systems, content management systems and traditional Web sites.
EDIT 1:
take a look at here also:
http://paulhammant.com/2012/02/13/client-side-mvc-frameworks-compared/
I'm hoping someone can advise me on how to solve my networking scenario. Both the client and server are to be C# / .NET based.
I basically want to invoke some kind of web service from my client in order to retrieve both binary data (e.g. files) and serialised objects and lists of objects (e.g. database query results).
At the moment, I'm using ASPX pages, using the query string to provide parameters and I get back either the binary data, or the binary data of the serialised messages. This affords me a lot of flexbility, and I can choose how to transmit the data, perform simulatanous requests, cancel ongoing requests, etc. Since I can control the serialised format, I can also deserialise lists of objects as they are received which is crucial.
My problem isn't a problem as such, but this feels a little hack-ish and I can't help but wonder if there are better ways to go about it. I'm considering moving on to WCF or perhaps another technology to see if it helps. However, I need to know if it helps with my scenarios above that is;
Can a WCF method return a list of objects, and can the client receive the items of this list as they arrive as opposed to getting the entire list on completion (i.e. streaming). Does anyone know of any examples of this?
Am I likely to get any performance benefits from this? I don't know how well ASPX pages are tuned for this, as it surely isn't their primary purpose.
Are there any other approaches I should consider?
Thanks for your time spent reading this. I hope you can help.
WCF does not natively support streamed collections. (Which are not the same as Streaming Message Transfer)
However, see this blog post.
I recommend that you use ASHX files (Generic Handlers) instead of ASPX pages (Web Forms), as they have far less overhead.