Skip to main content

Api

The cloud.Api resource represents a collection of HTTP endpoints that can be invoked by clients over the internet. APIs often serve as the front door for applications to access data, business logic, or functionality from your backend services.

The Api resource models an endpoint as a collection of routes, each mapped to an event handler function. A route is a combination of a path, like "/users/:userid" and a set of HTTP methods, like GET, POST, or DELETE. When a client invokes a route, the corresponding event handler function executes.

Usage

REST API

The following example shows a complete REST API implementation using cloud.Api, ex.Table & cloud.Counter

bring cloud;
bring ex;

let api = new cloud.Api();
// Used for generating unique id
let counter = new cloud.Counter();
// our employee database
let db = new ex.Table(
name: "employees",
primaryKey: "id",
columns: {
"name" => ex.ColumnType.STRING
}
);

api.get("/employees", inflight (request: cloud.ApiRequest): cloud.ApiResponse => {
let result = MutJson [];
let var i = 0;
for employee in db.list() {
result.setAt(i, employee);
i = i + 1;
}
return cloud.ApiResponse {
status: 200,
body: Json.stringify(result)
};
});


api.get("/employees/:id", inflight (request: cloud.ApiRequest): cloud.ApiResponse => {
let employee = db.get(request.vars.get("id"));
return cloud.ApiResponse {
status: 200,
body: Json.stringify(employee)
};
});

api.post("/employees", inflight (request: cloud.ApiRequest): cloud.ApiResponse => {
if let body = request.body {
let employeeData = Json.parse(body);
let id = "{counter.inc()}";
db.insert(id, employeeData);
return cloud.ApiResponse {
status: 201,
body: id
};
}
});

api.put("/employees/:id", inflight (request: cloud.ApiRequest): cloud.ApiResponse => {
if let body = request.body {
let employeeData = Json.parse(body);
let id = request.vars.get("id");
db.update(id, employeeData);
return cloud.ApiResponse {
status: 200,
body: Json.stringify(employeeData)
};
}
});

api.delete("/employees/:id", inflight (request: cloud.ApiRequest): cloud.ApiResponse => {
let id = request.vars.get("id");
db.delete(id);
return cloud.ApiResponse {
status: 204
};
});

Target-specific details

Simulator (sim)

The sim implementation of cloud.Api uses nodejs express.

AWS (tf-aws and awscdk)

The AWS implementation of cloud.Api uses Amazon API Gateway.

Azure (tf-azure)

🚧 Not supported yet (tracking issue: #625)

GCP (tf-gcp)

🚧 Not supported yet (tracking issue: #624)

API Reference

Api

Functionality shared between all Api implementations.

Initializers

bring cloud;

new cloud.Api(props?: ApiProps);
NameTypeDescription
propsApiPropsNo description.

propsOptional

Methods

Preflight Methods
NameDescription
connectAdd a inflight handler to the api for CONNECT requests on the given path.
deleteAdd a inflight handler to the api for DELETE requests on the given path.
getAdd a inflight handler to the api for GET requests on the given path.
headAdd a inflight handler to the api for HEAD requests on the given path.
optionsAdd a inflight handler to the api for OPTIONS requests on the given path.
patchAdd a inflight handler to the api for PATCH requests on the given path.
postAdd a inflight handler to the api for POST requests on the given path.
putAdd a inflight handler to the api for PUT requests on the given path.

connect
connect(path: str, inflight: IApiEndpointHandler, props?: ApiConnectOptions): void

Add a inflight handler to the api for CONNECT requests on the given path.

pathRequired
  • Type: str

The path to handle CONNECT requests for.


inflightRequired

The function to handle the request.


propsOptional

Options for the route.


delete
delete(path: str, inflight: IApiEndpointHandler, props?: ApiDeleteOptions): void

Add a inflight handler to the api for DELETE requests on the given path.

pathRequired
  • Type: str

The path to handle DELETE requests for.


inflightRequired

The function to handle the request.


propsOptional

Options for the route.


get
get(path: str, inflight: IApiEndpointHandler, props?: ApiGetOptions): void

Add a inflight handler to the api for GET requests on the given path.

pathRequired
  • Type: str

The path to handle GET requests for.


inflightRequired

The function to handle the request.


propsOptional

Options for the route.


head
head(path: str, inflight: IApiEndpointHandler, props?: ApiHeadOptions): void

Add a inflight handler to the api for HEAD requests on the given path.

pathRequired
  • Type: str

The path to handle HEAD requests for.


inflightRequired

The function to handle the request.


propsOptional

Options for the route.


options
options(path: str, inflight: IApiEndpointHandler, props?: ApiOptionsOptions): void

Add a inflight handler to the api for OPTIONS requests on the given path.

pathRequired
  • Type: str

The path to handle OPTIONS requests for.


inflightRequired

The function to handle the request.


propsOptional

Options for the route.


patch
patch(path: str, inflight: IApiEndpointHandler, props?: ApiPatchOptions): void

Add a inflight handler to the api for PATCH requests on the given path.

pathRequired
  • Type: str

The path to handle PATCH requests for.


inflightRequired

The function to handle the request.


propsOptional

Options for the route.


post
post(path: str, inflight: IApiEndpointHandler, props?: ApiPostOptions): void

Add a inflight handler to the api for POST requests on the given path.

pathRequired
  • Type: str

The path to handle POST requests for.


inflightRequired

The function to handle the request.


propsOptional

Options for the route.


put
put(path: str, inflight: IApiEndpointHandler, props?: ApiPutOptions): void

Add a inflight handler to the api for PUT requests on the given path.

pathRequired
  • Type: str

The path to handle PUT requests for.


inflightRequired

The function to handle the request.


propsOptional

Options for the route.


Static Functions

NameDescription
onLiftTypeA hook called by the Wing compiler once for each inflight host that needs to use this type inflight.
renderCorsHeadersGenerates an object containing default CORS response headers and OPTIONS response headers.
renderOpenApiPathConverts input path to a valid OpenAPI path (replaces : based path params with {}).

onLiftType
bring cloud;

cloud.Api.onLiftType(host: IInflightHost, ops: MutArray<str>);

A hook called by the Wing compiler once for each inflight host that needs to use this type inflight.

The list of requested inflight methods needed by the inflight host are given by ops.

This method is commonly used for adding permissions, environment variables, or other capabilities to the inflight host.

hostRequired

opsRequired
  • Type: MutArray<str>

renderCorsHeaders
bring cloud;

cloud.Api.renderCorsHeaders(corsOptions?: ApiCorsOptions);

Generates an object containing default CORS response headers and OPTIONS response headers.

corsOptionsOptional

The CORS options to generate the headers from.


renderOpenApiPath
bring cloud;

cloud.Api.renderOpenApiPath(path: str);

Converts input path to a valid OpenAPI path (replaces : based path params with {}).

pathRequired
  • Type: str

The path to convert (assumes path is valid).


Properties

NameTypeDescription
nodeconstructs.NodeThe tree node.
urlstrThe base URL of the API endpoint.

nodeRequired
node: Node;
  • Type: constructs.Node

The tree node.


urlRequired
url: str;
  • Type: str

The base URL of the API endpoint.


Structs

ApiConnectOptions

Options for Api patch endpoint.

Initializer

bring cloud;

let ApiConnectOptions = cloud.ApiConnectOptions{ ... };

ApiCorsOptions

Cors Options for Api.

Initializer

bring cloud;

let ApiCorsOptions = cloud.ApiCorsOptions{ ... };

Properties

NameTypeDescription
allowCredentialsboolWhether to allow credentials.
allowHeadersMutArray<str>The list of allowed headers.
allowMethodsMutArray<HttpMethod>The list of allowed methods.
allowOriginstrThe allowed origin.
exposeHeadersMutArray<str>The list of exposed headers.
maxAgedurationHow long the browser should cache preflight request results.

allowCredentialsOptional
allowCredentials: bool;
  • Type: bool
  • Default: false

Whether to allow credentials.


allowHeadersOptional
allowHeaders: MutArray<str>;
  • Type: MutArray<str>
  • Default: ["Content-Type", "Authorization"]

The list of allowed headers.


Example

["Content-Type"]
allowMethodsOptional
allowMethods: MutArray<HttpMethod>;
  • Type: MutArray<HttpMethod>
  • Default: [HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE, HttpMethod.HEAD, HttpMethod.OPTIONS]

The list of allowed methods.


Example

[HttpMethod.GET, HttpMethod.POST]
allowOriginOptional
allowOrigin: str;
  • Type: str
  • Default: "*"

The allowed origin.


Example

"https://example.com"
exposeHeadersOptional
exposeHeaders: MutArray<str>;
  • Type: MutArray<str>
  • Default: []

The list of exposed headers.


Example

["Content-Type"]
maxAgeOptional
maxAge: duration;

How long the browser should cache preflight request results.


ApiDeleteOptions

Options for Api put endpoint.

Initializer

bring cloud;

let ApiDeleteOptions = cloud.ApiDeleteOptions{ ... };

ApiGetOptions

Options for Api get endpoint.

Initializer

bring cloud;

let ApiGetOptions = cloud.ApiGetOptions{ ... };

ApiHeadOptions

Options for Api patch endpoint.

Initializer

bring cloud;

let ApiHeadOptions = cloud.ApiHeadOptions{ ... };

ApiOptionsOptions

Options for Api patch endpoint.

Initializer

bring cloud;

let ApiOptionsOptions = cloud.ApiOptionsOptions{ ... };

ApiPatchOptions

Options for Api patch endpoint.

Initializer

bring cloud;

let ApiPatchOptions = cloud.ApiPatchOptions{ ... };

ApiPostOptions

Options for Api post endpoint.

Initializer

bring cloud;

let ApiPostOptions = cloud.ApiPostOptions{ ... };

ApiProps

Options for Api.

Initializer

bring cloud;

let ApiProps = cloud.ApiProps{ ... };

Properties

NameTypeDescription
corsboolOptions for configuring the API's CORS behavior across all routes.
corsOptionsApiCorsOptionsOptions for configuring the API's CORS behavior across all routes.

corsOptional
cors: bool;
  • Type: bool
  • Default: false, CORS configuration is disabled

Options for configuring the API's CORS behavior across all routes.

Options can also be overridden on a per-route basis. (not yet implemented) When enabled this will add CORS headers with default options. Can be customized by passing corsOptions


Example

true
corsOptionsOptional
corsOptions: ApiCorsOptions;
  • Type: ApiCorsOptions
  • Default: Default CORS options are applied when cors is set to true allowOrigin: "*", allowMethods: [ HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.HEAD, HttpMethod.OPTIONS, ], allowHeaders: ["Content-Type", "Authorization"], exposeHeaders: [], allowCredentials: false,

Options for configuring the API's CORS behavior across all routes.

Options can also be overridden on a per-route basis. (not yet implemented)


Example

{ allowOrigin: "https://example.com" }

ApiPutOptions

Options for Api put endpoint.

Initializer

bring cloud;

let ApiPutOptions = cloud.ApiPutOptions{ ... };

ApiRequest

Shape of a request to an inflight handler.

Initializer

bring cloud;

let ApiRequest = cloud.ApiRequest{ ... };

Properties

NameTypeDescription
methodHttpMethodThe request's HTTP method.
pathstrThe request's path.
queryMutMap<str>The request's query string values.
varsMutMap<str>The path variables.
bodystrThe request's body.
headersMutMap<str>The request's headers.

methodRequired
method: HttpMethod;

The request's HTTP method.


pathRequired
path: str;
  • Type: str

The request's path.


queryRequired
query: MutMap<str>;
  • Type: MutMap<str>

The request's query string values.


varsRequired
vars: MutMap<str>;
  • Type: MutMap<str>

The path variables.


bodyOptional
body: str;
  • Type: str

The request's body.


headersOptional
headers: MutMap<str>;
  • Type: MutMap<str>

The request's headers.


ApiResponse

Shape of a response from a inflight handler.

Initializer

bring cloud;

let ApiResponse = cloud.ApiResponse{ ... };

Properties

NameTypeDescription
bodystrThe response's body.
headersMutMap<str>The response's headers.
statusnumThe response's status code.

bodyOptional
body: str;
  • Type: str
  • Default: no body

The response's body.


headersOptional
headers: MutMap<str>;
  • Type: MutMap<str>
  • Default: {}

The response's headers.


statusOptional
status: num;
  • Type: num
  • Default: 200

The response's status code.


CorsHeaders

Type definition for CORS headers which includes default and options headers.

Initializer

bring cloud;

let CorsHeaders = cloud.CorsHeaders{ ... };

Properties

NameTypeDescription
defaultResponseMutMap<str>Default CORS response headers.
optionsResponseMutMap<str>CORS options response headers.

defaultResponseRequired
defaultResponse: MutMap<str>;
  • Type: MutMap<str>

Default CORS response headers.


optionsResponseRequired
optionsResponse: MutMap<str>;
  • Type: MutMap<str>

CORS options response headers.


Protocols

IApiEndpointHandler

Inflight client: @winglang/sdk.cloud.IApiEndpointHandlerClient

A resource with an inflight "handle" method that can be passed to one of the Api request preflight methods.

IApiEndpointHandlerClient

Inflight client for IApiEndpointHandler.

Methods

NameDescription
handleInflight that will be called when a request is made to the endpoint.

handle
inflight handle(request: ApiRequest): ApiResponse?

Inflight that will be called when a request is made to the endpoint.

requestRequired

Enums

HttpMethod

Allowed HTTP methods for a endpoint.

Members

NameDescription
GETGet.
HEADHead.
POSTPost.
PUTPut.
DELETEDelete.
CONNECTConnect.
OPTIONSOptions.
PATCHPatch.

GET

Get.


HEAD

Head.


POST

Post.


PUT

Put.


DELETE

Delete.


CONNECT

Connect.


OPTIONS

Options.


PATCH

Patch.