LoopBack 4 offers thepackage out of the box, which provides an HTTP/HTTPS-based server calledRestServer
for handling REST requests.
In order to use it in your application, your application class needs to extendRestApplication
to provide an instance of RestServer listening on port 3000.The following example shows how to use RestApplication
:
The REST server can be configured by passing a rest
property inside yourRestApplication options. For example, the following code customizes the portnumber that a REST server listens on.
const app = new RestApplication({
rest: {
port: 3001,
},
});
There are a few options under rest.openApiSpec
to configure how OpenAPI specis served by the given REST server.
- servers: Configure servers for OpenAPI spec
- setServersFromRequest: Set
servers
based on HTTP request headers, default tofalse
- disabled: Set to
true
to disable endpoints for the OpenAPI spec. It willdisable API Explorer too. - endpointMapping: Maps urls for various forms of the spec. Default to:
{
'/openapi.json': {version: '3.0.0', format: 'json'},
'/openapi.yaml': {version: '3.0.0', format: 'yaml'},
}
const app = new RestApplication({
rest: {
openApiSpec: {
servers: [{url: 'http://127.0.0.1:8080'}],
setServersFromRequest: false,
endpointMapping: {
'/openapi.json': {version: '3.0.0', format: 'json'},
'/openapi.yaml': {version: '3.0.0', format: 'yaml'},
},
},
});
Configure the API Explorer
LoopBack allows externally hosted API Explorer UI to render the OpenAPIendpoints for a REST server. Such URLs can be specified with rest.apiExplorer
:
- url: URL for the hosted API Explorer UI, default to
https://loopback.io/api-explorer
. - httpUrl: URL for the API explorer served over plain http to deal with mixedcontent security imposed by browsers as the spec is exposed over
http
bydefault. See . Defaultto the value ofurl
.
Disable redirect to API Explorer
To disable redirect to the externally hosted API Explorer, set the config optionrest.apiExplorer.disabled
to true
.
const app = new RestApplication({
rest: {
apiExplorer: {
disabled: true,
},
},
Use a self-hosted API Explorer
Enabling HTTPS for the LoopBack REST server is just a matter of specifying theprotocol as https
and specifying the credentials.
In the following app, we configure HTTPS for a bare minimum app using a key +certificate chain variant.
import {RestApplication, RestServer, RestBindings} from '@loopback/rest';
import * as fs from 'fs';
export async function main() {
const options = {
rest: {
protocol: 'https',
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem'),
},
};
const app = new RestApplication(options);
app.handler(handler => {
handler.response.send('Hello');
});
await app.start();
const url = app.restServer.url;
console.log(`Server is running at ${url}`);
}
Customize CORS
is enabledby default for REST servers with the following options:
{
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
maxAge: 86400,
}
The application code can customize CORS via REST configuration:
For a complete list of CORS options, seehttps://github.com/expressjs/cors#configuration-options.
Express settings
Override the default express settings and/or assign your own settings:
const app = new RestApplication({
rest: {
expressSettings: {
'x-powered-by': false,
env: 'production',
...
},
},
});
Sometime it’s desirable to expose REST endpoints using a base path, such as/api
. The base path can be set as part of the RestServer configuration.
const app = new RestApplication({
basePath: '/api',
},
});
The RestApplication
and RestServer
both provide a basePath()
API:
const app: RestApplication;
// ...
app.basePath('/api');
With the basePath
, all REST APIs and static assets are served on URLs startingwith the base path.
Configure the router
The router can be configured to enforce strict
mode as follows:
strict
is true:- request
/orders
matches route/orders
but not/orders/
- request
/orders/
matches route/orders/
but not/orders
strict
is false (default)- request
/orders
matches route/orders
first and falls back to/orders/
- request
/orders/
matches route/orders/
first and falls back to/orders
Seestrict routing
at for moreinformation.
Configure the request body parser options
We can now configure request body parser options as follows:
The value of rest.requestBodyParser
will be bound toRestBindings.REQUEST_BODY_PARSER_OPTIONS. Seefor more details.
import {Application} from '@loopback/core';
import {RestServer} from '@loopback/rest';
export class HelloWorldApp extends Application {
constructor() {
super();
// This server instance will be bound under "servers.fooServer".
this.server(RestServer, 'fooServer');
// Creates a binding for "servers.MQTTServer" and a binding for
// "servers.SOAPServer";
this.servers([MQTTServer, SOAPServer]);
}
You can also add multiple servers in the constructor of your application classas shown here.
- Learn more about