Spring Restful services GET and POST methods - restful-url

Probably a simple question on REST...
How do I pass the GET variables to the function in the below code
#GET
#Produces("application/json")
#Path("/loginresult.json/{userid}/{pwd}")
{
public List<SecurityBean> getAuthenticationResult(){
return authenticationAPI.getAuthenticationResult();
}
I wan't to pass the userid and pwd coming in url to the getAuthenticationResult() function
Also How can I pass POST parameters ?

for GET use #QueryParam,
for POSt use #FormParam,
for Cookie use #CookieParam.

Use following Code
#POST
#Produces("application/json")
#Path("/loginresult.json/{userid}/{pwd}")
{
public List<SecurityBean> getAuthenticationResult(#FormParam("uName") String uName,#FormParam("pwd") String pwd){
return authenticationAPI.getAuthenticationResult();
}

Related

How to create GET method in API controller with parameters (e.g. sort query or search query)?

I have an API controller and GET method like this :
public IEnumerable<CountryDTO> GetContries(string sortOrder, string searchString)
{
return countryRepository.GetCos(sortOrder, searchString);
}
but when I try to get url api/countries
I`ve got an error like:
The requested resource does not support http method 'GET'.
How to fix this problem?
Try to explicitly mark the method [HttpGet] and make the following change to your method.
[HttpGet]
public IEnumerable GetCountries(string sortOrder, string searchString)
{
return countryRepository.GetCos(sortOrder, searchString).ToList();
}
Also, I would recommend before you make the change, simply test your method using a tool like SOAPUI or Fiddler. See if you are able to get a response. That way you know for sure that problem is not in the basics of the method formation.
[HttpGet]
public string GetCountries(string sortOrder, string searchString)
{
return ("returns list of countries");
}

Adding new parameter to a web API action method without disturbing the existing contract

I have an action method already written in my web api 2.0 project. I would like to add a new parameter without disturbing the existing contract. What is the best way to do that? Appreciate any best practice hints on this :)
Here's the code sample of what I intend to do:
Existing code:
[Route("{myId}",Name="MyId")]
Public IHttpActionResult Get(String myId)
{
//Some more code here
}
Url: http://localhost:8888/webapi/1111
Expecting to do something like the below:
//I want to keep the route name same for backwards compatibility.
[Route("{myId}/{myName}",Name="MyId")]
Public IHttpActionResult Get(String myId,string? myName)
{
//Some more code here
}
Url: http://localhost:8888/webapi/1111/John
The Url mentioned above hits the method rightly, but I never get the second parameter (myName) populated with John.
Thanks everyone for any help towards this.
Sree.
In your example you have myName as string? which is not allowed as:
The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'
A test controller was created to implement you action
[RoutePrefix("webapi")]
public class TestsController : ApiController {
[HttpGet]
[Route("{myId}/{myName}", Name = "MyId")]
public IHttpActionResult Get(string myId, string myName) {
//Some code to show the values of the parameters
return Ok(new { myId = myId, myName = myName });
}
}
When tested with webapi/1111/John the following response is returned
{"myId":"1111","myName":"John"}
which does include the value for MyName as John
If backwards uri webapi/1111 is tried, a NotFound response is returned as the template does not match the new action.
To fix this you need to make the myName parameter optional. To learn more about that check
Optional URI Parameters and Default Values
The new route will look like
//NOTICE THE `?` ON THE {myName} TEMPLATE
[Route("{myId}/{myName?}", Name = "MyId")]
public IHttpActionResult Get(string myId, string myName = null) {...}
You will notice that myName was made optional in the route {myId}/{myName?} and in the action parameter (string myId, string myName = null)
Now when tested with webapi/1111 the following response is returned
{"myId":"1111","myName":null}
Which would match your expected result for backwards compatibility.
String is a reference type so you don't need to make it nullable, it already is. Remove the '?' and remove the Name from the attribute. What happens then?

How should I design MVC to conditionally return JSON or pretty HTML?

I have data that will either be consumed by a human or a web service. The REST url is:
http://host.com/movies/detail/1
http://host.com/movies/detail/The Shawshank Redemption (1994)
What convention should I follow to conditionally return JSON or HTML? Should I add a parameter such as "?json" or should I look at the client headers,.. some variation of both?
If I do a variation of both, if a conflict is found which takes precedent?
Check whether the Request is Ajax. You may use the Request.IsAjaxRequest() method which returns true/false.
public ActionResult details(string id)
{
var movieViewModel=movieService.GetMovieDetails(id);
If(Request.IsAjaxRequest())
{
// return Json now
return Json(movieViewModel,JsonRequestBehavior.AllowGet);
}
// Not an ajax request, Let's return Normal View (HTML)
return View(movieViewModel);
}
UNIT TESTING ASPECT : Request.IsAjaxRequest() is not unit test friendly! So if you are worried about unit tests, You can write your IsAjaxRequest property and put in your basecontroller class and use it.
public class BaseController : Controller
{
protected bool IsAjaxRequest()
{
//Using this method instead of Request.IsAjaxRequest() because
//IsAjaxRequest is static and not mockable ! (not unit test friendly)
var isAjax = Request.Headers["X-Requested-With"];
if (isAjax != null && isAjax.ToUpper() == "XMLHTTPREQUEST")
return true;
return false;
}
}
Now inherit your controller from this BaseController.
public class HomeController : BaseController
{
public ActionResult details(string id)
{
var movieViewModel=movieService.GetMovieDetails(id);
If(IsAjaxRequest)
{
// return Json now
return Json(movieViewModel,JsonRequestBehavior.AllowGet);
}
// Not an ajax request, Let's return Normal View (HTML)
return View(movieViewModel);
}
}
You could also use:
[HttpGet]
public ActionResult() {
// Return HTML
}
[HttpPost]
public ActionResult() {
// Assuming Ajax is of the type post
}
Just another solution if all your Ajax is using post.
I prefer using a parameter explicit in the URL because that way building REST petitions is easy for developers, self explanatory and with no surprises (do you have to guess default format? or see "difficult" to see HTTP headers). You decide:
if you have many options for formats you can use format=json
you can go with json parameter, but it is not pretty because you have to pair it with a value json=true, json=1. Besides you can set json=1&xml=1&html=1, harder to handle.
the twitter way is to emulate an extension such as call.json or call.xml (e.g. https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline)
I recommend don't tie together a kind of petition and a format. Let your API clients decide, ajax-json is commonly used, but not all develepers use it that way. Maybe I am writing a terminal application with no ajax, maybe I want to do a wget to your API and still get json.

How to fetch an unknown number of POST parameters in ASP.NET MVC?

I have the following controller:
class FooController : Controller
{
public ActionResult SomeAction(id)
{
Type t = Type.GetType(id);
object o = Activator.CreateInstance(t);
((MyModel)o).ParseParamaters(PostParameters); // I need to pass the post parameters here
//...
}
}
I would like to fetch all the POST parameters that were submitted.
How can it be done?
You do that with
[HttpPost]
public ActionResult SomeAction(id, FormCollection form)
{
//do what you want with the collection
}
I believe Request.Querystring is just a collection of strings, so you could pass it as a parameter to ParseParameters. Or you could just pass the whole Request object.
But I'm wondering why you'd want to, when there's perfectly good model binding built into MVC to do all the heavy lifting for you. http://weblogs.asp.net/nmarun/archive/2010/02/25/asp-net-mvc-model-binding.aspx

How to know if HTTP request is GET or POST in Struts 2 action?

Is there a way to know in Struts2 action's method if this is GET or POST request?
Your action should implent org.apache.struts2.interceptor.ServletRequestAware, so your action class should have something like
private HttpServletRequest httpRequest;
// ...
public void setServletRequest(HttpServletRequest request) {
this.httpRequest = request;
}
Then just do:
String method = httpRequest.getMethod() ;
You can use HTTPServletRequest.getMethod() to find out that and handle accordingly in action.
HTTPServletRequest.getMethod()
If you don't want to implement ServletRequestAware just for this, you can get the method with 1 line:
String method = ServletActionContext.getRequest().getMethod();

Resources