ASP.NET Web API (Part 1)

Earlier this week I blogged about the release of the ASP.NET MVC 4 Beta.  ASP.NET MVC 4 is a significant update that brings with it a bunch of great new features and capabilities.  One of the improvements I’m most excited about is the support it brings for creating “Web APIs”.  Today’s blog post is the first of several I’m going to do that talk about this new functionality.

Web APIs

The last few years have seen the rise of Web APIs - services exposed over plain HTTP rather than through a more formal service contract (like SOAP or WS*).  Exposing services this way can make it easier to integrate functionality with a broad variety of device and client platforms, as well as create richer HTML experiences using JavaScript from within the browser.  Most large sites on the web now expose Web APIs (some examples: Facebook, Twitter, LinkedIn, Netflix, etc), and the usage of them is going to accelerate even more in the years ahead as connected devices proliferate and users demand richer user experiences.

Our new ASP.NET Web API support enables you to easily create powerful Web APIs that can be accessed from a broad range of clients (ranging from browsers using JavaScript, to native apps on any mobile/client platform).  It provides the following support:

  • Modern HTTP programming model: Directly access and manipulate HTTP requests and responses in your Web APIs using a clean, strongly typed HTTP object model.  In addition to supporting this HTTP programming model on the server, we also support the same programming model on the client with the new HttpClient API that can be used to call Web APIs from any .NET application.
  • Content negotiation: Web API has built-in support for content negotiation – which enables the client and server to work together to determine the right format for data being returned from an API.  We provide default support for JSON, XML and Form URL-encoded formats, and you can extend this support by adding your own formatters, or even replace the default content negotiation strategy with one of your own.
  • Query composition: Web API enables you to easily support querying via the OData URL conventions.  When you return a type of IQueryable<T> from your Web API, the framework will automatically provide OData query support over it – making it easy to implement paging and sorting.
  • Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request and convert those message parts into .NET objects which can be used by Web API actions.  Web API supports the same model binding and validation infrastructure that ASP.NET MVC supports today.
  • Routes: Web APIs support the full set of routing capabilities supported within ASP.NET MVC and ASP.NET today, including route parameters and constraints. Web API also provides smart conventions by default, enabling you to easily create classes that implement Web APIs without having to apply attributes to your classes or methods.  Web API configuration is accomplished solely through code – leaving your config files clean.
  • Filters: Web APIs enables you to easily use and create filters (for example: [authorization]) that enable you to encapsulate and apply cross-cutting behavior.
  • Improved testability: Rather than setting HTTP details in static context objects, Web API actions can now work with instances of HttpRequestMessage and HttpResponseMessage – two new HTTP objects that (among other things) make testing much easier. As an example, you can unit test your Web APIs without having to use a Mocking framework.
  • IoC Support: Web API supports the service locator pattern implemented by ASP.NET MVC, which enables you to resolve dependencies for many different facilities.  You can easily integrate this with an IoC container or dependency injection framework to enable clean resolution of dependencies.
  • Flexible Hosting: Web APIs can be hosted within any type of ASP.NET application (including both ASP.NET MVC and ASP.NET Web Forms based applications).  We’ve also designed the Web API support so that you can also optionally host/expose them within your own process if you don’t want to use ASP.NET/IIS to do so.  This gives you maximum flexibility in how and where you use it.

Learning More

Visit www.asp.net/web-api to find tutorials on how to use ASP.NET Web API.  You can also watch me talk about and demo ASP.NET Web API in the video of my ASP.NET MVC 4 Talk (I cover it 36 minutes into the talk). 

In my next blog post I’ll walk-through how to create a new Web API, the basics of how it works, and how you can programmatically invoke it from a client.

Hope this helps,

Scott

P.S. In addition to blogging, I use Twitter to-do quick posts and share links. My Twitter handle is: @scottgu

47 Comments

  • I dreamed this day would come :-)

  • These videos are good. Thanks for sharing this source.

  • More, more, more! :)

  • Will it support OAuth like other popular APIs like e.g. Dropbox does?

  • @Uwe,

    >>>>>> Will it support OAuth like other popular APIs like e.g. Dropbox does?

    Yes - we are planning to have built-in support for using OAuth with the final release. This isn't built-into the beta, but we are planning to build it in with the next drop.

    Hope this helps,

    Scott

  • Will we get any performance gains/better resource utilization from converting a simple (private) API from just using MVC controllers to using Web API?

  • @Scott
    What do you mean by "have built-in support for using OAuth" ?
    Does it mean that next drop will have some OAuth 2.0 server build-in ?
    If yes that would be great...

  • Been reading a ton about Web Api. Looks awesome. Just want to throw my vote in for tools to auto-generate the client side data classes and infrastructure like traditional web services have. As easy as it is to set up the server side, if there isn't support for the client side then traditional SOAP services are still easier.

  • What difference between ASP.Net
    MVC and Web-API?
    I see it the same..

  • Looking forward to hearing more. Sounds like WCF-style tweak on MVC at the moment.

  • Dan Roth did a great talk on Web API on channel 9 earlier this week. If you'd like to see some great hands on demos take a peek at the show.

  • How would Web API fit into WebForm application?
    There was ASP.NET Page Method, but how'd things get evolved?
    You won't leave WebForm developer behind, will you?

  • @Scott,

    Does this mean you can send a request with a SWT token in the header?

  • This is awesome!

    When can we expect RTM version? Will it ship with .NET or sooner?

  • Detailed migration path from WCF Web API preview 6, please. Pretty please.

  • Is there a way to have both REST and SOAP (WSDL) in the same service? I'd like to switch to this, as it's way way better than WCF, but I'm afraid my boss will want me to still expose a WSDL. I tried searching but couldn't find anything.

  • Do we have to use MVC to use Web API?

  • Could you elaborate on the OAuth plans or point to more info? I'm currently working on an API and we're at the point where we have to layer OAUth on top. If you're planning this already, it may change our plans. Will OAuth 2.0 support be included and will it be the traditional 3-legged OAuth, or will other permutations be allowed (such as 1-legged?)

  • @logic_rabbit,

    >>>>>> What do you mean by "have built-in support for using OAuth" ? Does it mean that next drop will have some OAuth 2.0 server build-in ? If yes that would be great...

    We are still finalizing the exact plans - but yes, having built-in OAuth 2.0 support is something we'd like to be able to enable.

    Hope this helps,

    Scott

  • @kinect dev,

    >>>>>> Been reading a ton about Web Api. Looks awesome. Just want to throw my vote in for tools to auto-generate the client side data classes and infrastructure like traditional web services have. As easy as it is to set up the server side, if there isn't support for the client side then traditional SOAP services are still easier.

    You will see some auto-generated classes for some use-cases with some of the higher-level libraries we are doing on top of Web API. For example, some of the data libraries we are doing will do this.

    One of the things we are trying to do, though, and which you'll see in some of the posts I'll do next is to make it trivially easy to call and use Web API from any language or platform (.NET, JS, iOS, etc) so that you don't have to rely on code generation to get things done.

    Hope this helps,

    Scott

  • @Pragmatist,

    >>>>> What difference between ASP.Net MVC and Web-API?

    Web API Controllers are designed primarily for scenarios where you are exposing/returning/updating data, whereas the default MVC Controllers are typically used to return HTML.

    You'll see as I continue the series that ApiController base class is very familiar with the Controller base class and shares concepts like filters, validation, routing, etc. You can use both within the same application.

    Hope this helps,

    Scott

  • @Panya,

    >>>>>> How would Web API fit into WebForm application?

    You can definitely use Web API within WebForms applications. Henrik has a good post on how to do this: http://blogs.msdn.com/b/henrikn/archive/2012/02/23/using-asp-net-web-api-with-asp-net-web-forms.aspx

    Hope this helps,

    Scott

  • @Marcel,

    >>>>> Is there a way to have both REST and SOAP (WSDL) in the same service? I'd like to switch to this, as it's way way better than WCF, but I'm afraid my boss will want me to still expose a WSDL. I tried searching but couldn't find anything.

    Web API doesn't directly support WSDL or SOAP. You can use the WCF REST support if you want to use a WCF/WSDL based model to support both SOAP and REST though.

    Hope this helps,

    Scott

  • @Alex,

    >>>>>> Could you elaborate on the OAuth plans or point to more info? I'm currently working on an API and we're at the point where we have to layer OAUth on top. If you're planning this already, it may change our plans. Will OAuth 2.0 support be included and will it be the traditional 3-legged OAuth, or will other permutations be allowed (such as 1-legged?)

    We are still finalizing the exact plans - but yes, having built-in OAuth 2.0 support is something we'd like to be able to enable. I'll post more once we have our OAuth plans a little more backed.

    Hope this helps,

    Scott

  • Please forgive my lack of knowledge ... is it possible to upload an image using API? Thx.

  • Why two kind of controllers? Why ApiController do not derive from Controller?

    Why for a unique URL "/products", couldn't I have a unique controller with method routing constrained (and prioritized) by Http Accept header values? Something like:

    public class ProductsController : ... {

    // /products[/index] for text/html
    public ActionResult Index() { ... }

    // /products for application/json|xml
    public IQueryable GetAllProducts() { ... }

    ...
    }

  • I'm getting this error when trying to create an MVC4 project ... "GetExportedValue cannot be called before prerequisite import 'NuGet.VisualStudio.VsSettings..ctor (Parameter = "solutionManager", ContractName= "NuGet.VisualStudio.ISolutionManager") has been set." ... any ideas?

    Thx!

  • i cant install MVC4Beta.
    error: 0x8004005 this products is incompatible with .net 4.5 developer preview.

    os:win7 sp1
    vs:2010 sp1
    .net framework:4

    please help me.

  • why not use WCF to build web api?

  • Can we override the content negotiation to handle headers like this:

    Accept: application/vnd.my-app+json; version=1.1

    This should return data in JSON format according to the v1.1 of the API.

    Thanks!

  • Can I still host this in appfabric like WCF and track the parameters that are passed into the api?

  • Great post, I enjoyed reading it! Keep posting good stuff like this.

  • Now, where does this leave the WCF Data Services framework? Should the ASP.NET Web API be used going forward?

  • I am struggling with ASP.NET web service now. thanks!

  • Hi Scott,

    Started watching your clip - with the new bundling and minification how can we handle versioning e.g. if there is a new version of a js file or css file...

    thanks
    Dean

  • Great article scott. Love the work you are doing! Chris.

  • I have mentioned this as a suggestion:

    http://aspnet.uservoice.com/forums/147201-web-api/suggestions/2619955-add-a-html-mediatypeformater-to-the-web-api

    but it was declined straight away (rather than letting the community comment and vote on the idea). I have seen at least one other comment on the forum asking for a way to combine the Web Api with MVC such that the razor / aspx handling of MVC can be used to render the returned data as HTML/XHTML in response to a request that it being handled by the Web API. Providing an "Inline" HTML representation at the same URL as the API is great for allowing client developers to explore your API and see help text from the browser... this gives a far better developer experience than having to use Fiddler to experiment with the API or having to append /help to a URI. The Inline HTML can contain the data returned from the URI as well as help, explantory text and schemas. The HTML can contain links to other resources etc.

  • Scott, how is ASP.NET Web API positioned in relation to WCF Data Services? Which would Microsoft recommend to build a RESTful hypermedia API over Entity Framework? Does ASP.NET Web API make it easy to return navigational properties like WCF Data Services? Is WCF Data Services going to be obsolete or deprecated in favor of ASP.NET Web API?

  • I would also like to hear the answer to fernandoacorreia's question. I'm designing an application which will consist of a Silverlight client and a set of REST services and I'm struggling to determine whether I should use the Web API or OData. As of write now, it's not clear how to implement hypermedia in the Web API. If I new how to do that, I think I would prefer to use the Web API over OData.

  • This is one amazing article! Thank you for posting this. You certainly have some agreeable opinions and views. Your blog provides a fresh look at the subject.

  • Is there any built in support for versioning your API? I.e. routing api/v1/conacts and api/v2/contacts to the correct handlers.

  • kjfbv

  • So what happens with WCF Data Services?

  • Hi,
    Another vote for fernandoacorreia's question. Hypermedia is Rest and some would argue that without it you are only at level 2 of Rest compliance. The samples that are on the WEB-API site are great introduction, but as soon as you need something like a Customer who has a list of Orders it becomes completely questionable as to how to do this. If there is a way to accomplish this, a simple example would be extremely helpful. I've talked with others who share this interest and concern. Could someone from the WEB-API give us an example/sample please?
    Given that - many will love this capability!
    regards

  • That's so great article Scott. I re-read two times your tutorial on how to use asp.net web api. It's so amazing.

  • I've been playing with WebAPI and noticed the ApiController is pretty slim in the overridable function department. Meaning, I don't see any counterparts to OnActionExecuting & OnActionExecuted for the normal MVC controller. Something like OnFormatOutputExecuting and OnFormatExecuting are also absent (the data-format corrolary to rendering a view in OnResultExecuting and OnResultExecuted). I found these methods invaluable on the MVC side, even if just for instrumentation & logging.

    Are there corresponding ways to monitor/inject myself into the API process?

  • So, how about that oauth2 support? It's relevant to my interests.

Comments have been disabled for this content.