Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API ResponseType for Single Integer

What is the "correct" way to have a call to a Web API REST service that simply returns a single integer?

I have no requirements here in terms of XML, JSON, or anything else. The call to the service just needs to return an integer.

Do I use the ResponseType attribute here?

I have the service return type as HttpResponseMessage, and for services such as something returning JSON I would set the Content property on this to StringContent with UTF8 "application/json".

But what is correct for a single integer?

like image 200
Patrick Avatar asked Dec 25 '22 07:12

Patrick


1 Answers

I recommend that you use the IHttpActionResult type for your API methods. It will allow you to use several different convenience methods for returning common responses. In your case it would just look like this:

public IHttpActionResult GetInteger() {
   // Ok is a convenience method for returning a 200 Ok response
   return Ok(1);
}

or if you wanted to return it wrapped in an object for easier JSON consumption an anonymous object is fine:

public IHttpActionResult GetInteger() {
   // Ok is a convenience method for returning a 200 Ok response
   return Ok(new {
      value = 1
   });
}

Documentation here

Summarized from the docs are some of the reasons why you would use IHttpActionResult:

  • Simplifies unit testing your controllers.
  • Moves common logic for creating HTTP responses into separate classes.
  • Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.
like image 123
Jesse Carter Avatar answered Dec 29 '22 07:12

Jesse Carter