HTTPController class

Base class for grouping response logic for a group of endpoints.

Instances of this class respond to HTTP requests. This class must be subclassed to provide any behavior. Instances are typically the last RequestController in a series of controllers. A new HTTPController instance must be created for each Request, therefore they must be added to a series of RequestControllers with generate. A Request must have passed through a Router prior to being delivered to an HTTPController.

The primary responsibility of an HTTPController is receive Requests and map the Request to an individual 'responder method' to generate a response. A responder method returns a Response wrapped in a Future and must have HTTPMethod metadata (e.g., httpGet or httpPost). It may also have HTTPPath, HTTPQuery and HTTPHeader parameters.

Requests sent to an HTTPController have already been routed according to their path by a Router. An HTTPController does further routing based on the HTTP method and path variables of the Request.

An HTTPController typically receives a group of routes from a Router that refer to a resource collection or individual resource. For example, consider the following route:

    router
      .route("/users/[:id]")
      .generate(() => new UserController());

The requests /users and /users/1 are both routed to an instance of UserController (a subclass of HTTPController) in this example. Responder methods would be implemented in UserController to handle both the collection (/users) and individual resource (/users/1) cases for each supported HTTP method the controller wants to provide.

In the above example, a UserController would implement both GET /users, GET /users/:id, and POST /users/ like so:

    class UserController extends HTTPController {
      // invoked for GET /users
      @httpGet
      Future<Response> getAllUsers() async
        => new Response.ok(await fetchAllUsers());

      // invoked for GET /users/[0-9]+
      @httpGet
      Future<Response> getOneUser(@HTTPPath("id") int id) async =>
        new Response.ok(await fetchOneUser(id));

      // invoked for POST /users
      @httpPost
      Future<Response> createUser() async =>
        return new Response.ok(await createUserFromBody(request.body.asMap()));
    }

The responder method is selected by first evaluating the HTTP method of the incoming Request. If no such method exists - here, for example, there are not httpPut or httpDelete responder methods - a 405 status code is returned.

After evaluating the HTTP method, path variables (using the :variableName syntax in Router) are evaluated next. If there are no path variables (e.g., /users), the responder method with no HTTPPath arguments is selected. Responder methods with HTTPPath parameters must have the exact number and matching names for each path variable parsed in the request. In the above example, the path variable is named id in Router.route and therefore the argument to HTTPPath is id.

If there is no responder method match for the incoming request's path variables, a 404 is returned and no responder method is invoked.

Responder methods may also have HTTPHeader and HTTPQuery parameters. Parameters in the positional parameters of a responder method are required; if the header or query value is omitted from a request, no responder method is selected and a 400 status code is returned.

HTTPHeader and HTTPQuery parameters in the optional part of a method signature are optional; if the header or query value is omitted from the request, the responder method is still invoked and those parameters are null. For example, the following requires that the request always contain the header X-Required, which will be parsed to int and available in requiredValue. If it contains email in the query string, that value will be available in emailFilter when this method is invoked. If it does not, the emailFilter is null.

    class UserController extends HTTPController {
      @httpGet
      Future<Response> getAllUsers(
        @HTTPHeader("X-Required") int requiredValue,
        {@HTTPQuery("email") String emailFilter}) async {
          ...
      }
    }

HTTPController subclasses may also declare properties that are marked with HTTPHeader and HTTPQuery, in which case all responder methods accept those header and query values.

  class UserController extends RequestController {
    @HTTPHeader("X-Opt") String optionalHeader;

    @httpGet getUser(@HTTPPath ("id") int userID) async {
      optionalHeader == request.innerRequest.headers["x-opt"]; // true

      return new Response.ok(await userWithID(userID));
    }
  }

Properties are optional by default. requiredHTTPParameter will mark them as required for all responder methods.

An instance of this type will decode the Request.body prior to invoking a responder method.

See further documentation here: http://aqueduct.io/docs/http/http_controller/

Inheritance
Implemented by
Annotations
  • @cannotBeReused

Constructors

HTTPController()

Properties

acceptedContentTypes List<ContentType>
Types of content this HTTPController will accept. [...]
read / write
pathVariables Map<String, String>
Parameters parsed from the URI of the request, if any exist. [...]
read-only
request Request
The request being processed by this HTTPController. [...]
read / write
responseContentType ContentType
The default content type of responses from this HTTPController. [...]
read / write
documentableChild APIDocumentable
Returns the next documentable object in a chain of documentable objects. [...]
read-only, inherited
hashCode int
The hash code for this object. [...]
read-only, inherited
logger Logger
An instance of the 'aqueduct' logger.
read-only, inherited
nextController RequestController
Receives requests that this controller does not respond to. [...]
read-only, inherited
policy CORSPolicy
The CORS policy of this controller.
read / write, inherited
runtimeType Type
A representation of the runtime type of the object.
read-only, inherited

Methods

didDecodeRequestBody(HTTPRequestBody decodedObject) → void
Callback to indicate when a request body has been processed. [...]
documentOperations(PackagePathResolver resolver) List<APIOperation>
Returns all APIOperations this object knows about.
documentResponsesForOperation(APIOperation operation) List<APIResponse>
Returns all APIResponses for operation.
processRequest(Request req) Future<RequestOrResponse>
Overridden by subclasses to modify or respond to an incoming request. [...]
willDecodeRequestBody(HTTPRequestBody body) → void
Callback invoked prior to decoding a request body. [...]
willProcessRequest(Request req) FutureOr<RequestOrResponse>
Executed prior to handling a request, but after the request has been set. [...]
applyCORSHeadersIfNecessary(Request req, Response resp) → void
inherited
documentAPI(PackagePathResolver resolver) APIDocument
Returns an entire APIDocument describing an OpenAPI specification. [...]
inherited
documentPaths(PackagePathResolver resolver) List<APIPath>
Returns all APIPath objects this instance knows about. [...]
inherited
documentRequestBodyForOperation(APIOperation operation) APIRequestBody
Returns all APIRequestBodys for operation.
inherited
documentSecuritySchemes(PackagePathResolver resolver) Map<String, APISecurityScheme>
Returns all APISecuritySchemes this instance knows about.
inherited
generate(RequestController instantiator()) RequestController
Sets the nextController that will receive a request after this one. [...]
inherited
handleError(Request request, dynamic caughtValue, StackTrace trace) Future<bool>
Sends an HTTP response for a request that yields an exception or error. [...]
inherited
listen(FutureOr<RequestOrResponse> process(Request request)) RequestController
Sets the nextController that will receive a request after this one. [...]
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a non-existent method or property is accessed. [...]
inherited
pipe(RequestController next) RequestController
Sets the nextController that will receive a request after this one. [...]
inherited
receive(Request req) Future
Delivers req to this instance to be processed. [...]
inherited
toString() String
Returns a string representation of this object.
inherited
willSendResponse(Response response) → void
Executed prior to Response being sent. [...]
inherited

Operators

operator ==(dynamic other) bool
The equality operator. [...]
inherited