I would like to generate an openapi.json file on a loopback 4 api without having to start the server and request the openapi endpoint. I could not find any way to do it in the loopback documentation.
Is there any way to generate that file ?
Method getApiSpec() from rest.server.ts @loopback/rest/rest.server.ts.
add method in index.ts:
// Node module: @loopback/example-express-composition
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import { ExpressServer } from './server';
import { ApplicationConfig } from '@loopback/core';
import { RequestContext } from '@loopback/rest';
export { ExpressServer };
export async function main(options: ApplicationConfig = {}) {
const server = new ExpressServer(options);
await server.boot();
await server.start();
console.log('Server is running at http://127.0.0.1:3000');
}
export async function getOpenApiJSONtoFile(options: ApplicationConfig = {}) {
const server = new ExpressServer(options);
await server.boot();
return server.lbApp.restServer.getApiSpec()
}
and create file for create json:
const application = require('./dist');
const fs = require('fs');
const config = {
rest: {
port: +process.env.PORT || 3000,
host: process.env.HOST || 'localhost',
openApiSpec: {
// useful when used with OpenAPI-to-GraphQL to locate your application
setServersFromRequest: true,
},
// Use the LB4 application as a route. It should not be listening.
listenOnStart: false,
},
};
application.getOpenApiJSONtoFile(config)
.then(result => {
let data = JSON.stringify(result);
fs.writeFileSync('openapi.json', data);
})
.catch(err => { console.log(err) });