DZone

Anatomy of an HTTP Service

A Ballerina service’s structure and its semantics are defined by the service type, i.e. the type of listener attached. Let’s take a look at how a basic HTTP service is structured in Ballerina. 

  • Service name: The service name represents the base path of the HTTP service. This is an optional value, where if it’s kept empty, the base path defaults to the value “/”.
  • Listener object: Provides an instance of http:Listener to bind to a specific host/port.
  • Resource: A resource represents a specific subpath that can be accessed in relation to the service base path.
    • Accessor: The HTTP method used to access the resource. These can be any HTTP method: e.g., “get”, “put”, “post”, “delete”. Only a single accessor can be associated with a single resource. If you need to support multiple HTTP methods to a single resource, you can define distinct service resources with the same name and different accessors. The special accessor “default” can be used to dispatch all the requests with the resource path, regardless of the HTTP method.
    • Name: The name represents the path of the resource in relation to the service base path. You can provide hierarchical values as well, e.g., “foo/bar”. In this case, the final path to this resource would be “/base/foo/bar”.
      The special name “.” is used to represent the service itself in a resource. Thus, requests that are directly sent to the base path will be dispatched to this resource.
       
    • Return type: This is an optional return type, which can be of type anydata or http:Response. An anydata return value would be returned with an HTTP status code 200 OK.

The full source code for the hello service above is shown below. 

Source: DZone