api

package
v2.0.0-beta.15 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MPL-2.0 Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package api serves a service's typed HTTP endpoints: methods declared as endpoints with an //encore:api directive, served from the service's own main.

It is Encore's API framework for Go, in a module of its own, framework.encore.dev/v2, with the errs package beside it, built on the Infra SDK (sdk.encore.dev/v2): a service that declares its API in a spec, or serves it with another framework, does not need it.

import "framework.encore.dev/v2/api"

A service opts in with the type "encore-api" in its encore.service.json, which makes its endpoints the service's API documentation:

{"name": "users", "lang": "go", "type": "encore-api"}

An endpoint is an exported method of a named type, anywhere in the service's directory, whose doc comment carries the directive:

type Service struct{ DB *postgres.Database }

type GetParams struct {
	ID     int64  `path:"id"`
	Fields string `query:"fields"`
	Locale string `header:"Accept-Language"`
}

// Get returns a user.
//
//encore:api expose=api method=GET path=/users/{id}
func (s *Service) Get(ctx context.Context, p *GetParams) (*User, error)

Encore's parser reads the directives, and the runtime config tells the program each endpoint's route and the method that serves it. The program hands the server the values whose methods those are:

func main() {
	srv := api.NewServer()
	api.Handle(srv, &users.Service{DB: db})
	encore.Start()
	if err := api.ListenAndServe(srv); err != nil {
		log.Fatal(err)
	}
}

Handle binds every endpoint of each value's type, and panics on a value whose type has none. An endpoint no value serves answers 501 Not Implemented, and is warned about once the server starts.

The directive

//encore:api is followed by options, fields and tags:

  • expose=api,admin, on the named gateways; an endpoint without it is private, reached only by the app's services, unless the service's "api"."expose" routes it. A bare expose is refused: an app has no default gateway;
  • raw, for an endpoint that takes the request itself;
  • sensitive, for an endpoint whose requests are recorded as only their method, route, status and timing;
  • method=GET,POST, path=/users/{id} and name=get_user;
  • tag:name.

The name defaults to the method's, the path to /<service>.<name>, and the methods to POST for an endpoint with a request, GET and POST for one without, and every method for a raw one.

Signatures

An endpoint is one of

func (r R) M(ctx context.Context) error
func (r R) M(ctx context.Context, req *Req) error
func (r R) M(ctx context.Context) (*Resp, error)
func (r R) M(ctx context.Context, req *Req) (*Resp, error)
func (r R) M(w http.ResponseWriter, req *http.Request) // raw

where Req and Resp are structs. The context is the request's, carrying its trace and Request Context (sdk.encore.dev/v2/reqctx).

Where each field travels

A request field tagged path:"name" is the route's {name} parameter; header:"Name", query:"name" and cookie:"name" place a field in a header, the query string or a cookie, and a name of "-" drops it. An untagged field is in the query string, named in snake_case (PageSize is page_size), for GET, HEAD and DELETE, and in the JSON body, as encoding/json/v2 names it, for every other method.

A path, query, header or cookie value is a string, a boolean, an integer or a float, or a named type of one, or a type with text methods (encoding.TextUnmarshaler, like time.Time, which takes RFC 3339); a query or header value may also be a slice of one, repeated. An empty value leaves a number or boolean zero, and a value that does not parse answers 400 Bad Request.

The body is decoded into the request with encoding/json/v2 and its default options, and may be empty; a field that travels elsewhere keeps the value its location gives it, whatever the body holds. So v2's rules apply: names match case-sensitively, duplicate names and invalid UTF-8 are refused, a nil slice or map is [] or {}, `json:",string"` quotes a number, an embedded map[string]T or jsontext.Value tagged `json:",embed"` takes the members no field does, and a time.Duration has no representation (encode one as a number of your choosing). The format tag option is not supported by the standard library's encoding/json/v2.

A response field tagged header:"Name" is a response header, left out of the body, and not sent when it is an empty string or slice. One tagged cookie:"name" sets a cookie: an http.Cookie (or a pointer to one) with its options, named by the tag when it names itself nothing, or a value; an empty one sets none. One tagged encore:"httpstatus", an integer, is the response's status code, 200 when it is zero. Every other field is in the JSON body, encoded with encoding/json/v2. A response of nil answers with the body null, and an endpoint without a response answers 200 with no body. A header named X-Encore-… is Encore's own, and no field's.

A route's last segment may be a wildcard, {*name} (written *name in the directive), taking the rest of the path: its field, tagged path:"name", is a string.

A request's body holds at most 2 MiB, or the directive's bodylimit= (bytes, with a unit like 4MiB, or none); a larger one answers 400 Bad Request. A raw endpoint reads its body itself.

Fields are found as encoding/json/v2 finds them: exported fields, and the fields of embedded structs (and of fields tagged `json:",embed"`) promoted into their parent; json:"-" drops an untagged one. A type with its own JSON or text methods is its body as they write and read it; only its location-tagged fields travel elsewhere.

Errors

An *errs.Error (framework.encore.dev/v2/errs) answers as the errs package encodes it, its status from its code. So does an error errs.Code knows the code of: a context's, sql.ErrNoRows (not_found), and a database error by its SQLSTATE, as already_exists for a unique violation. Any other error answers 500 with the code internal, telling the client nothing of it, and is logged. A panic in an endpoint is recovered, logged and answered the same way.

A failed call to another service, a *services.CallError (sdk.encore.dev/v2/services), is one: its code is the other service's answer to this one, not this endpoint's to its client, so an endpoint answers with a code of its own where it means one:

product, err := catalogopenapi.GetProduct(ctx, &catalogopenapi.GetProductInput{ID: id})
if services.Code(err) == services.NotFound {
	return nil, &errs.Error{Code: errs.NotFound, Message: "no such product"}
} else if err != nil {
	return nil, err // internal
}

A call that failed as its ctx was canceled, or ran out of time, still answers canceled or deadline_exceeded, as the context's error does.

Raw endpoints

A raw endpoint is an http.HandlerFunc: it reads the request and writes the response itself, its path parameters in r.PathValue.

Middleware

Server.Use adds net/http middleware around every endpoint, the first added outermost:

srv.Use(func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		slog.InfoContext(r.Context(), "request", "route", r.Pattern)
		next.ServeHTTP(w, r)
	})
})

Tracing

The server records a SERVER span for each request, from its arrival to its response, continuing the trace it came with and named after its route, as "GET /users/{id}", with the attributes of OpenTelemetry's HTTP semantic conventions. So it needs no otelhttp; wrapping it in otelhttp records a second span.

Outside Encore

Outside Encore, as under a plain go run, the program has no runtime config, and so no endpoints: Handle panics, saying so. Run the program with encore run.

Example

Serve a service's endpoints from its main.

package main

import (
	"context"
	"log"
	"log/slog"
	"net/http"

	"framework.encore.dev/v2/api"
	"framework.encore.dev/v2/errs"

	encore "sdk.encore.dev/v2"
)

// Users is the users service.
type Users struct {
	users map[int64]*User
}

// User is a user of the app.
type User struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

// GetParams are where Get's parameters travel: the path, a header and,
// untagged, the query string of a GET.
type GetParams struct {
	ID     int64  `path:"id"`
	Locale string `header:"Accept-Language"`

	Fields []string
}

// UserResponse is a user, with a header beside it.
type UserResponse struct {
	User

	Greeting string `header:"X-Greeting"`
}

// Get returns a user.
//
//encore:api expose=api method=GET path=/users/{id}
func (s *Users) Get(ctx context.Context, p *GetParams) (*UserResponse, error) {
	u, ok := s.users[p.ID]
	if !ok {
		return nil, &errs.Error{Code: errs.NotFound, Message: "no such user"}
	}
	greeting := "hello"
	if p.Locale == "sv" {
		greeting = "hej"
	}
	return &UserResponse{User: *u, Greeting: greeting}, nil
}

// CreateParams are the JSON body of a POST.
type CreateParams struct {
	Name string `json:"name"`
}

// Create adds a user.
//
//encore:api expose=api method=POST path=/users
func (s *Users) Create(ctx context.Context, p *CreateParams) (*User, error) {
	u := &User{ID: int64(len(s.users) + 1), Name: p.Name}
	s.users[u.ID] = u
	return u, nil
}

// Webhook takes the request itself.
//
//encore:api expose=api raw method=POST path=/webhooks/{provider}
func (s *Users) Webhook(w http.ResponseWriter, r *http.Request) {
	slog.InfoContext(r.Context(), "webhook", "provider", r.PathValue("provider"))
	w.WriteHeader(http.StatusAccepted)
}

func main() {
	srv := api.NewServer()
	api.Handle(srv, &Users{users: map[int64]*User{}})
	encore.Start()
	if err := api.ListenAndServe(srv); err != nil {
		log.Fatal(err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handle

func Handle(s *Server, values ...any)

Handle binds the endpoints of each value's type: every method of it whose //encore:api directive declares an endpoint of the service, by the handler the runtime config names for each of its routes. Pass a pointer for a type whose endpoints have pointer receivers.

Handle panics on what is a mistake in the program: a value whose type has no endpoints of the service, an endpoint a value given earlier already serves, a method whose signature is not an endpoint's, a request or response field that cannot travel where its tags place it, a call once the server has begun serving. Outside Encore there are no endpoints, so Handle always panics there.

func ListenAndServe

func ListenAndServe(h http.Handler) error

ListenAndServe serves h, typically a *Server, as encore.Serve does: on the address Encore assigns the service, ENCORE_LISTEN_ADDR (outside Encore on the port PORT names, or 8080), with each request traced, until Encore's graceful shutdown. A *Server warns of the endpoints no value serves as it begins serving.

Once the shutdown begins, on SIGTERM or SIGINT, the server takes no new requests, and Encore closes the infrastructure only once the requests in flight are answered. ListenAndServe returns once the shutdown is complete: nil if it completed in time, else why not. It returns at once if the server cannot listen, as when its address is taken. The process's exit is main's:

if err := api.ListenAndServe(srv); err != nil {
	log.Fatal(err)
}

Outside Encore it handles SIGTERM and SIGINT itself, the same way.

Types

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server serves the endpoints of the services the process serves. It is an http.Handler: ListenAndServe serves it where Encore assigns the service, and it may be mounted in another mux too.

Make it with NewServer, bind its endpoints with Handle, and add middleware with Server.Use, all before it serves its first request.

Example (Mount)

Mount the endpoints in a mux that serves other handlers too.

package main

import (
	"context"
	"log"
	"log/slog"
	"net/http"

	"framework.encore.dev/v2/api"
	"framework.encore.dev/v2/errs"

	encore "sdk.encore.dev/v2"
)

// Users is the users service.
type Users struct {
	users map[int64]*User
}

// User is a user of the app.
type User struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

// GetParams are where Get's parameters travel: the path, a header and,
// untagged, the query string of a GET.
type GetParams struct {
	ID     int64  `path:"id"`
	Locale string `header:"Accept-Language"`

	Fields []string
}

// UserResponse is a user, with a header beside it.
type UserResponse struct {
	User

	Greeting string `header:"X-Greeting"`
}

// Get returns a user.
//
//encore:api expose=api method=GET path=/users/{id}
func (s *Users) Get(ctx context.Context, p *GetParams) (*UserResponse, error) {
	u, ok := s.users[p.ID]
	if !ok {
		return nil, &errs.Error{Code: errs.NotFound, Message: "no such user"}
	}
	greeting := "hello"
	if p.Locale == "sv" {
		greeting = "hej"
	}
	return &UserResponse{User: *u, Greeting: greeting}, nil
}

// CreateParams are the JSON body of a POST.
type CreateParams struct {
	Name string `json:"name"`
}

// Create adds a user.
//
//encore:api expose=api method=POST path=/users
func (s *Users) Create(ctx context.Context, p *CreateParams) (*User, error) {
	u := &User{ID: int64(len(s.users) + 1), Name: p.Name}
	s.users[u.ID] = u
	return u, nil
}

// Webhook takes the request itself.
//
//encore:api expose=api raw method=POST path=/webhooks/{provider}
func (s *Users) Webhook(w http.ResponseWriter, r *http.Request) {
	slog.InfoContext(r.Context(), "webhook", "provider", r.PathValue("provider"))
	w.WriteHeader(http.StatusAccepted)
}

func main() {
	srv := api.NewServer()
	api.Handle(srv, &Users{users: map[int64]*User{}})

	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	mux.Handle("/", srv)
	encore.Start()
	if err := api.ListenAndServe(mux); err != nil {
		log.Fatal(err)
	}
}

func NewServer

func NewServer() *Server

NewServer returns a server of the endpoints of the services the process serves, as the runtime config describes them. None is bound yet: Handle binds them.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves r: with the endpoint its route is bound to, a 501 Not Implemented for one of an endpoint no value serves, and a 404 or 405 for a request no route matches.

func (*Server) Use

func (s *Server) Use(mw ...func(http.Handler) http.Handler)

Use adds net/http middleware around the server's endpoints, the first added outermost. Middleware runs for every request the server takes, after its Request Context and trace are in the request's context, and before its endpoint, whose route r.Pattern names as net/http.ServeMux does ("GET /users/{id}"; empty for a request no route matches). It panics once the server has begun serving.

Example

Log every request, with its route and how long it took.

package main

import (
	"context"
	"log"
	"log/slog"
	"net/http"
	"time"

	"framework.encore.dev/v2/api"
	"framework.encore.dev/v2/errs"

	encore "sdk.encore.dev/v2"
)

// Users is the users service.
type Users struct {
	users map[int64]*User
}

// User is a user of the app.
type User struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

// GetParams are where Get's parameters travel: the path, a header and,
// untagged, the query string of a GET.
type GetParams struct {
	ID     int64  `path:"id"`
	Locale string `header:"Accept-Language"`

	Fields []string
}

// UserResponse is a user, with a header beside it.
type UserResponse struct {
	User

	Greeting string `header:"X-Greeting"`
}

// Get returns a user.
//
//encore:api expose=api method=GET path=/users/{id}
func (s *Users) Get(ctx context.Context, p *GetParams) (*UserResponse, error) {
	u, ok := s.users[p.ID]
	if !ok {
		return nil, &errs.Error{Code: errs.NotFound, Message: "no such user"}
	}
	greeting := "hello"
	if p.Locale == "sv" {
		greeting = "hej"
	}
	return &UserResponse{User: *u, Greeting: greeting}, nil
}

// CreateParams are the JSON body of a POST.
type CreateParams struct {
	Name string `json:"name"`
}

// Create adds a user.
//
//encore:api expose=api method=POST path=/users
func (s *Users) Create(ctx context.Context, p *CreateParams) (*User, error) {
	u := &User{ID: int64(len(s.users) + 1), Name: p.Name}
	s.users[u.ID] = u
	return u, nil
}

// Webhook takes the request itself.
//
//encore:api expose=api raw method=POST path=/webhooks/{provider}
func (s *Users) Webhook(w http.ResponseWriter, r *http.Request) {
	slog.InfoContext(r.Context(), "webhook", "provider", r.PathValue("provider"))
	w.WriteHeader(http.StatusAccepted)
}

func main() {
	srv := api.NewServer()
	api.Handle(srv, &Users{users: map[int64]*User{}})
	srv.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			next.ServeHTTP(w, r)
			slog.InfoContext(r.Context(), "request", "route", r.Pattern, "took", time.Since(start))
		})
	})
	encore.Start()
	if err := api.ListenAndServe(srv); err != nil {
		log.Fatal(err)
	}
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL