krakenjs / swaggerize-express

Design-driven apis with swagger 2.0 and express.
Other
354 stars 81 forks source link

Return JSON in stead of HTML when validation fails #129

Open ghost opened 6 years ago

ghost commented 6 years ago

Hi guys,

Small (noob) question about swaggerize-express

It's awesome swaggerize-express validates incoming requests against the swagger schema. But I was wondering, how can I customise the response in not returning HTML formatted response, but a JSON response when validation fails?

Regards.

gonenduk commented 6 years ago

The validation is done in a middleware function in the route system. It simply calls the next one with an error if it finds anything. This is the standard express way. For example, if your api is under /api - add this as the last route declared: app.use('/api', (err, req, res, next) => { res.status(err.status).json(err); });

ghost commented 6 years ago

Ok, what you're trying to say is:

According to the readme of swaggerize-express:

var http = require('http');
var express = require('express');
var swaggerize = require('swaggerize-express');

app = express();

var server = http.createServer(app);

app.use(swaggerize({
    api: require('./api.json'),
    docspath: '/api-docs',
    handlers: './handlers'
}));

server.listen(port, 'localhost', function () {
    app.swagger.api.host = server.address().address + ':' + server.address().port;
});

I should add the following (just before server.listen()), like so (when base path is /api):

var http = require('http');
var express = require('express');
var swaggerize = require('swaggerize-express');

app = express();

var server = http.createServer(app);

app.use(swaggerize({
    api: require('./api.json'),
    docspath: '/api-docs',
    handlers: './handlers'
}));

app.use('/api', (err, req, res, next) => {
  res.status(err.status).json(err);
});

server.listen(port, 'localhost', function () {
    app.swagger.api.host = server.address().address + ':' + server.address().port;
});