How to create Http Response with Dart - rest

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()
;
}

Related

Get location fragment with Fetch API redirect response

I am trying to get the redirect response location fragment of a fetch API request. But I can't figure how to access it, if possible.
The context is that I am doing an OpenID Connect request in implicit flow, for a WebRTC Identity Proxy assertion generation.
OIDC specs define the answer of the request as:
When using the Implicit Flow, all response parameters are added to the
fragment component of the Redirection URI
HTTP/1.1 302 Found
Location: https://client.example.org/cb#
access_token=SlAV32hkKG
...
So I'm making the request with fetch set in manual mode. But the response is then an opaque-redirect filtered response, which hides the location header. (https://fetch.spec.whatwg.org/#concept-filtered-response-opaque-redirect)
Other mode for fetch are error and follow which would not help. While XHR automatically follows the redirect so would not help either. I may be missing something from the fetch API, but it seems to be something hidden on purpose.
Could someone gives me a way to access this information (or a confirmation it's impossible) ?
Is there any alternative to fetch and XHR to make this request, which would allow to access the redirect location header?
Since XHR automatically / opaquely follows redirects (in the event you're using the whatwg-fetch polyfill for example), one possible solution is to check the response.url of the fetch resolution, to see if it matches a redirect location that you expect.
This only helps if the possible redirect locations are limited or match some pattern --- for instance, if you could expect at any time to be redirect to /login:
function fetchMiddleware(response) {
const a = document.createElement('a');
a.href = response.url;
if (a.pathname === '/login') {
// ...
} else {
return response;
}
}
fetch(`/api`)
.then(fetchMiddleware)
.then(function (response) {
// ...
});
fetch isn't able to polyfill the entire standard. Some notable differences include:
Inability to set the redirect mode.
See David Graham comment on the Disable follow redirect:
This is a nice addition to the Fetch API, but we won't be able to polyfill it with XMLHttpRequest. The browser navigates all redirects before returning a result, so there is no opportunity to interrupt the redirect flow.
My Solution:
1). First solution: we are sending 200 status and redirect url(in the http header) from the server and client is redirecting based on that.
2). Second solution: Server could also redirect to with 301 and redirect url. I think, This is the best solution(i.e if we consider SEO).

How to code the Web Api Route, Controller for texting

I need to create a REST API Web Service using MVC4 Web Api that will be consumed by Twilio. I need to be able to accept Twilio's HTTP POST for receiving SMS from the user and for responding. So if the user texts a word "Join" or "My Order" then they would call my API using the URL that I have given and I should be sending the Welcome Message for join and the Order List for the text "My Order" and so on. How the heck do I do that? Do I need a single controller or multiple? How would I route this? Please help. Totally lost :-(
Twilio evangelist here.
Twilios HTTP requests are no different than any other HTTP client. So if you want to use Web API as your Twilio SMS URL, then you would just create a Post method and in the method definition, specify the parameters you want to capture from the request.
Twilio sends along a bunch if info with each request, like the to & from phone numbers and the body of the message. You can use model binding to grab this:
public HttpResponseMessage Post(string Body) {
//your code here
// if you want to return TwiML commands, use
// us the TwilioResponse object
return Request.CreateResponse(HttpStatusCode.OK, [your twiml]);
}
Twilio will made its request with an Accept header of text/xml, so WEb API should automatically try to return your TwiML commands as XML.
This blog post has more details on using Web API with Twilio:
http://www.twilio.com/blog/2012/11/building-twilio-apps-using-asp-net-mvc-4-web-api.html
Hope that helps.

Zend Framework set HTTP response code from inside a Handler

I'm developing a REST API using Zend Framework 1.12.3. I would like to know whether it's possible to set a HTTP response code from inside a Handler.
I'm using the Handler to check the "Accept" header. In case the requested format type is not supported, I should set a 415 HTTP error (Unsupported Media Type). However, I'm not able to set a response code from inside the Handler.
What do you mean by handler?
You can set a response code anywhere you have access to the Response object.
Technically, you can access the Response object nearly anywhere (after Bootstrap, at least) using:
$response = Zend_Controller_Front::getInstance()->getResponse();
The set your response code using:
$response->setHttpResponseCode($code);
It's most natural to do this in controllers since each controller already has a reference to the Response object:
$this->_response

In ASP.Net Web API, how do you fake PUT and DELETE?

I'm experimenting with ASP.Net Web API, which, by convention, splits controller methods into a Restful style of Get(), Put, Post and Delete. My question is how does one handle the PUT and DELETE requests that might come from a non-Ajax browser request.
So, let's say that I have foobar with id = 123. A normal fetch request would be
/foobars/123
To delete the item, the Restful way would be to issue:
DELETE /foobars/123
However, PUT and DELETE are not browser standards and do not have enough major browser support to be trusted if your request is coming from a non-Ajax browser request. So a common accepted workaround is:
POST /foobars/123?_method=DELETE (source: Restful Web Services)
For the new ASP.Net Web API, is there a best practice / common approach for working with this problem? What I want is for anything with a _method=DELETE to be routed to the DELETE() method in the controller and _method=PUT to be routed to the PUT() method of a controller.
You can easily achieve this using a DelegatingHandler.
So you would code:
public class HttpMethodHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var queryString = HttpUtility.ParseQueryString(request.RequestUri.Query);
if(!string.IsNullOrEmpty(queryString["_method"]))
{
request.Method = new HttpMethod(queryString["_method"]);
}
return base.SendAsync(request, cancellationToken);
}
}
And then add the handler to the pipeline. I have a blog on that.

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.