How do I create a REST GET endpoint in EK9?

← Web Services · Ref: Q199

EK9 has a built-in 'defines service' construct for REST endpoints. Services declare URI paths and methods that map to HTTP operations.

SERVICE DEFINITION

Define a service with a base URI path:

  defines service
    Info :/info

The service name 'Info' is bound to the '/info' path.

GET METHOD

Named methods default to GET:

  welcome() as GET for :/welcome
    <- response as HTTPResponse: ...

HTTPRESPONSE TRAIT

Return an HTTPResponse from service methods. Use a dynamic class with trait delegation:

  () with trait HTTPResponse
    override content()
      <- rtn as String: "Hello"
    override status() as pure
      <- rtn as Integer: 200

APPLICATION REGISTRATION

Register services in an application:

  defines application
    MyApp
      register Info()

See Q200 for CRUD operators. See Q201 for HTTP responses. See Q112 for full service example. See Q111 for components.

See Q657 for URI mapping. See Q659 for HTTPResponse.

Example

defines module qa.web.restget

  defines text for "en"

    WelcomeText
      greeting()
        "Welcome to the EK9 Service"

  defines service

    Info :/info open

      welcome() as GET for :/welcome
        <- response as HTTPResponse: () with trait HTTPResponse
          text <- WelcomeText("en")

          override cacheControl() as pure
            <- rtn as String: "no-store"
          override contentType() as pure
            <- rtn as String: "text/plain"
          override contentLanguage() as pure
            <- rtn as String: "en"
          override content()
            <- rtn as String: text.greeting()
          override status() as pure
            <- rtn as Integer: 200
          default operator ?

  defines application

    WebApp
      register Info()

  defines program

    RestGetDemo()
      stdout <- Stdout()

      stdout.println("Service registered with application")
      stdout.println("GET /info/welcome returns welcome text")
      stdout.println("HTTPResponse provides status, content, headers")

Common mistakes

E50060 — The WelcomeText text construct expects a String locale parameter. Passing an Integer triggers E50060 — constructor not resolved. See ek9 -h E50060 for details.

Incorrect:

text <- WelcomeText(42)

Correct:

text <- WelcomeText("en")
Other ways to ask this
  • How do I define a service in EK9?
  • How do I build a web API endpoint in EK9?
  • How do I define a REST endpoint in EK9?

Coming from another language?

Java: JAX-RS @GET @Path or Spring @GetMapping. Python: Flask @app.route('/path'). Rust: actix-web or axum handler functions. Go: http.HandleFunc('/path', handler). Kotlin: Ktor routing DSL. EK9: language-level 'defines service' with :/path URIs, named methods default to GET.

Keywords: path, http, endpoint, define, uri, response, rest, api, get, service