Can I get request header and response header for web service function? - rest

I am using Java with Apache CXF to write the backend for AngularJS (single-page web site). In my REST service, I need access to the header of the http request (i.e. parameters and cookies) and I need access to the response header also (i.e. parameters and cookies). The main reason for this is security, authentication purposes and session management. Those are important reasons.
Is there a way of getting both of these structures in Apach CXF RESTfull code?

You can inject request by using #Context [javax.ws.rs.core.Context]
public Response myRest(#Context HttpServletRequest request /*, other parameters if you have like #QueryParam */ ){
request.getCookies();
request.getUserPrincipal();
}
You can set cookie or header in response as bellow
ResponseBuilder builder = Response.ok(); //Response.status(500) either way
builder.cookie(arg0);
builder.header(arg0, arg1);
return bulider.build();

Related

How to create Http Response with Dart

I was trying to follow along with one of the Dart HttpServer examples from GitHub, and, while it does show how to create and handle routes, I'm still at a loss on how to produce and send an HttpResponce in response to a specific url being requested.
For example, while working with WebAPI, I would have an Api Controller, in which I could explicitly define an action for GET, PUT, DELETE and POST verbs, and return an appropriate HttpResponse with a resource from each such method.
Does anyone know how this typical CRUD business is done using Dart as an Http server?
Once you receive a HttpRequest you need to use the response attribute to answer.
void sendOk(HttpRequest request, [content]) {
request.response
..statusCode = HttpStatus.OK
..write(content)
..close()
;
}

How do websites like twitter parse return type in REST

How does websites like Twitter structure their server side for APIs in which there can be multiple return types?
For ex:
https://dev.twitter.com/docs/api/1.1/post/statuses/update
In this link, you can find that their example resource url is "https://api.twitter.com/1.1/statuses/update.json"
Using the ".json" extension, they differentiate between the return type. My questions basically is, if this is the method that they use, then do parse the url and get the extension using normal string manipulation, or is their a built in support in REST that is capable of doing so.
Also, is it better to have multiple APIs for multiple return types, or can there be a single API that can have multiple return types?
In Java, the specification JAX-RS provides the #Produces annotation. Setting
#Produces("application/json")
on a method will make this method match any request with the HTTP header
Accept: application/json
Obviously Twitter is doing something else. With JAX-RS you could use path matching.
#Produces("application/json")
#Path("/1.1/statuses/update.json")
could be the annotations for a method the prodcues application/json while
#Produces("application/xml")
#Path("/1.1/statuses/update.xml")
could be the annotations that produce application/xml.
I'd advise not to go the Twitter way of putting the content type into the URI. Instead use the proper HTTP tools of content negotiation with the HTTP headers Accept and Content-Type.

Restful web service GET request parameters

I'm using fiddler to test a Web API service I'm writing.
I know I can pass parameters to a RESTful web service in the querystring with a request like -
www.example.com/api/Book?Id=123&category=fiction.
Are there other ways of passing the parameters to the service, while still using a GET.
There are many parts of the HTTP request which you can use to pass parameters, namely the URI, headers and body. GET requests don't have bodies (some frameworks actually allow that, but they're not common so for all purposes, let's just assume that they can't), so you're limited to the headers and the URI.
In the URI you can pass parameters in different places:
Query string (as you're already doing)
Ex.: www.example.com/api/Book?Id=123&category=fiction
Request path
Many frameworks will allow you to get parameters to your actions from paths in the request URI. With ASP.NET Web API you'd typically do that using routing
Ex.: www.example.com/api/Book/fiction/123
In the fragment, or the part of the URI after the # character. See the URI RFC, section 3.5.
Ex.: www.example.com/api/Book?Id=123&category=fiction#somethingElse
You can also pass paramters in the HTTP request headers. One parameter which is honored by the ASP.NET Web API is the Accept header, which is used when doing content negotiation. You can also expect custom parameters from those headers, and read them in your actions (or even have value providers which will read them and map them to the parameters in the methods themselves).

Consuming a RESTful web service using Apache Camel

I am trying to consume a restful Web service using camel.
For that I am configuring dynamic endpoint url as the RESTful url is created at the runtime. Everytime I am checking if the particular endpoint url is registered as a route in my camel context using following method of CamelContext class.
Endpoint hasEndpoint(String uri);
In this case, if the endpoint is not registered then I add a route to my camel context using a custom Route Builder.
I am using camel HTTP component for this. This is working fine for me as of now.
However, I believe performance wise this is not good as everytime I have to check if a route is registered with the camel context and if not then register the same before making the webservice call.
Can some body please tell me if there is a better way to consume RESTful Web services in camel?
I also want to know if the RESTful webservice I am consuming uses OAuth 2.0 protocol, do I need to change anything in my code as I am just consuming it?
Regards, Nilotpal
Thanks for your reply.
I am checking if the route is already exists to make sure I don't end up adding duplicate route(s) to the camel context.
Regarding long lived routes and route dynamics, can u please explain a bit regarding this? How do I implement route dynamics?
It would also be helpful if you could point me to some CXF-RS producer example.. I read the documentation of CXFRS but could not understand it clearly.
Thanks
Nilotpal
Exactly why do you need to check if the route is registred or not before making the call? You should perhaps setup a more long lived route and route dynamic towards resfull resources.
As for Rest with camel, I think the HTTP component does a great job, but there are higher level components to use as well, more designed for REST.
CXFRS and Restlet, producer examples for restlet can be found in the Apache Camel source unit tests, such as this RestletProducerGetTest.java.
As for oAuth 2.0, Camel has some oAuth support built-in, especially for google. Look for the gauth component. There is even a tutorial, however it might not be aligned with your case, it still might give some background so you could solve your issues: http://camel.apache.org/tutorial-oauth.html
CamelContext context = new DefaultCamelContext();
My Aim
I am trying to intercept the incoming request and based on the ip of the incoming request i want to invoke dynamic endpoint of get offers
context.addRoutes(new RouteBuilder(){
public void configure(){
from("jetty:localhost:9000/offers")
.process(new Processor(){
public void process(Exchange exchange) throws Exception {
//getting the request object
HttpServletRequest req = exchange.getIn().getBody(HttpServletRequest.class);
//Extracting information from the request
String requestIP=req.getRemoteAddr();
/**
* After getting the ip address i do necessay processing
* and then add a property to exchange object.
* Destination ip address is the address to which i want to
* send my request
*/
exchange.setProperty("operatorAddress",destinationIpAddress);
}
})
.to("direct:getOffers")
.end();
}
});
Now i will invoke the getOffers endpoint
so first i will register it
context.addRoutes(new RouteBuilder(){
public void configure(){
from("direct:getOffers")
.toD("jetty:${property.operatorAddress}/api/v2.0/offers?
bridgeEndpoint=true")
.end();
}
});
so we can access the operatorAddress property of exchange object as
${property.operatorAddress}
also when we have dynamic routes then we need to call
.toD() and not .to()

Adding More parameters to REST HTTP GET

I am trying to access a REST web service using HTTP GET request.
For a example following URI provides Rest web service that return all the available parts for the given category.
http://localhost:8080/mycompany/parts/category
I want to authenticate/authorize users who are accessing above REST request in each time and I want to pass User authentication details (User Name and Token) with the HTTP Get Request.
Is there a possibility to cater to the above requirement in REST HTTP GET request (using HTTP header or query parameters)?
or
Is it better to use HTTP POST instead of HTTP GET?
Since you are getting information, you should use "Get". Here's the code that I use (it is Restlet based) for adding the oauth_token to the request...
import org.restlet.data.Reference;
import org.restlet.ext.oauth.OAuthUser;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
Reference commitsRef = new Reference(Consts.RESOURCE_BASE + "commitments/");
OAuthUser u = (OAuthUser) request.getClientInfo().getUser();
String token = u.getAccessToken();
ref.addQueryParameter("oauth_token", token);
ClientResource commitsResource = new ClientResource(getContext(), commitsRef);
Representation commitsRep = commitsResource.get();
As mentioned, this is Restlet based, but there is probably something similar in the framework you are using. (And if you are not using a framework, Restlet can make this easier).
if you are using restlet than good because restlet have rich api for rest framework
but without this if you want to authenticate than
you can do same thing with GET or POST
but send your credential data trough cookie
and read same cookie using #CookieParam from server side
in this way you can easily authenticate user.