Best practice for validating API input in Node.js? [closed] - node.js

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am developing a mobile app, with the backend in Node.js. Users will interact with the platform almost exclusively through the mobile app. As part of the backend, I am exposing multiple APIs to be utilized by the mobile app -- for example: an API to create an account, send a message, post a picture, etc.
What is best practice to validate the API input?
My thought is to create a module for each API, whose purpose is to extract, sanitize, and validate the relevant attributes from the http-request. For example, the "create an account" API will have an associated AccountCreationRequest module with a validate method in which all account-creation-specific validations will be defined. Each specific validation can then be performed by libraries such as express validator and validator.
exports.AccountCreationRequest = {
init: function(request) {
... extract attributes ...
},
sanitizeAndValidate: function() {
... use express-validator/validator on
attributes such as username, email, etc ...
},
isValid: function() {
... return result of validation ...
}
};
Then, when the backend API receives a request,
var accountCreationRequest = AccountCreationRequest.init(httpRequest);
accountCreationRequest.sanitizeAndValidate();
if (accountCreationRequest.isValid()) {
... store in database and notify client of success ...
} else {
... notify client of failure ...
}
My concern is that N APIs will require N request-validation-modules. However, since each API is unique, I don't think there is much opportunity for code reuse.

If you use express, you can do something like
app.use('/private', function(req, res, next) {
if (/*some condition to check for authentication*/) {
next();
} else { //unauthorized
res.status(401).send('not authorized, please authenticate');
}
});
that will filter everything under the /private path through your authentication condition. You can also use wildcards in the path if you prefer.

Related

How to create custom endpoints on the fly with nodejs [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have a website and when I click on a button I want to generate a custom link for the user, a link that it will be a endpoint to my nodejs server. My question is: how can this be accomplished ? I think I need to make a basic endpoint in my server that will be called when I press that button in my website and then, based on a custom property in the request's body, it will generate another endpoint, a custom endpoint for that user. How can I do this ? Any help or documentation would be appreciated.
Usually, this would be done with a parameter added to a fixed part of the URL. You then define a route for the fixed part of the URL and the code for that route then examines the parameter and acts accordingly. This way, you're dynamically generating parameters, but all the new parameters all go through the same route definition and the same code.
You can either use a dynamic portion of the URL path or a query parameter. Here is an example of each:
// dynamic path segment
// example url /dyn/dieutaoc
app.get("/dyn/:id", (req, res) => {
// use req.params.id to access the dynamic part of this path
});
// dynamic query parameter
// example url /dyn?id=dieutaoc
app.get("/dyn", (req, res) => {
// use req.query.id to access the dynamic part of this path
});

Internal API calls and communication between NextJS app and express server [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 months ago.
Improve this question
I have a NextJS app with a custom express server. My pages/index.js is making an internal call to my express route /api/users. This is done using isomorphic-unfetch inside getinitialprops() like this:
const res = await fetch('http://localhost:3000/api/users');
My custom express server on top of NextJS has API routes that send back JSON data. Like so:
//some code before
const app = next({ dev })
const handle = app.getRequestHandler()
let apiRoutes = require('./routes/apiRoutes.js');
app.prepare().then(() => {
const server = express()
server.use('/api', apiRoutes);
server.get('*', (req, res) => {
return handle(req, res)
})
//more code
So my question is, is this the way to communicate between the my client side code and server side code? If so:
How do I protect these endpoints so that the user doesn't just type in myNextJSwebsite.com/api/users and get a JSON response?
This is a common pattern to separate between api & renderer.
In order to secure your api end-point you will need to implement some kind of authorization, there is common lib for auturization in express, called passport, you can check the types, it supports most of the common methods.
I personally prefer the JWT way, because it allows to work with many instances of my server due to the fact that there are no user session on the server.

Concerns about separating front-end and back-end with a NodeJS UI server [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
During the last months, we at work have been looking for a solution to the following problem: front-end developers can't easily modify the appearance of the website without the help of back-end devs.
Our culture as a team is mostly based on full-stack frameworks such as Symfony 2 and Ruby on Rails. We use templating engines but the templates are mostly written by backend-devs according to designers' markups.
The step we are considering to make is separating that monolithic architecture into a backend rest API and a NodeJS server as "UI server". The NodeJS server would handle the client request, consume the backend API and return a rendered template. By specifying clearly the API and the JSONs served, frontend and backend devs could then work in parallel with less problems. More info here: http://www.nczonline.net/blog/2013/10/07/node-js-and-the-new-web-front-end/
The thing is, we strongly believe that this separation is a good thing from an architecture POV, but we fear about the drawbacks. We suspect that it will make things way harder. None of us in the team has never worked with this kind of architectures, so any hint or experience about that would be very valuable.
Is it worth it? When? Why?
What you need to do, is to have a clear line that separates your front-end from back-end. Then whatever the front-end needs from the backend-end team, it will documented comprehensively.
Let's say what you currently have is something like this:
app.get('/', function (req, res) {
database.query('select * from user', function (err, result) {
res.render(result);
});
});
But then then you want to make it like this:
in UI server:
app.get('/', function (req, res) {
request('apiServer/user', function (err, result) {
res.render(result);
});
});
in API server:
app.get('/user', function (req, res) {
database.query('select * from user', function (err, result) {
res.send(result);
});
});
This is good. This will separate the front-end and back-end, but not only logically but also physically by being in different servers.
I believe if they are under the same server it will be just ok. Instead of above, just have them in different files:
in user.js:
exports.getAll = function (cb) {
database.query('select * from user', cb);
};
in server.js:
var user = require('./user');
app.get('/', function (req, res) {
user.getAll(function (err, result) {
res.render(result);
});
});
Why this is better than your solution? Because it separates touching database, and rendering the data, and also it doesn't have a extra http round trip.
Following a MVC pattern, you put files that are like user.js in a models directory, you put files like server.js in a controller directory. You make sure both are documented for front-end developers.
Now if your front-end developers are just gonna make UI changes, they will just touch the HTML files. If they want to add a section with data, they will read the backend documentation, they will add another call to the model to get the data they in the respective controller that renders the HTML.
Just make sure you will standardize everything, so when something new comes along, programmers in your team can somehow predict how the interface is going to be, use a good ORM to the heavy lifting on making database calls. If using an ORM is not your choice then make good abstractions.
So your application in layers can be like this:
Database --> ORM --> Models --> Controllers --> Views(HTML files)
Now the front-end developers, work on the right side the above diagram. They only need to know the documented API of their left side if it's nicely abstracted away, but they don't need to know how it works. Anyone who works on the controllers, only need to know the documented API of their left side which is Models. You can continue it all the way to the database on the left.
Then on each layer you can have unit tests and integration tests all the way to the front to make sure the interfaces are consistent.
And if you're team is large, with a large code base, make sure you always keep the backward compatibility in your interfaces, but with warnings in logs for deprecated stuff. Never try to break anything.

How to call external REST webservices inside Liferay portlet? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have a web app that exposes REST webservices.
I want to call those web services using javascript\jQuery (ajax)
Basically I want to render the contents returned by the REST service & perform CRUD openations (which will call other REST services of the external web app)
Anyone has some pointers, articles, sample code that shows how to do it?
Thanks
If I understand your question correctly, there's nothing Liferay-specific in calling external webservices, so you can use any tutorial you find on the web. As you're mentioning you want to use jquery, I assume that those calls will be made from the browser - the only thing that you need to do in Liferay is to make sure that jquery is loaded - for this you can use your theme: Edit portal-normal.vm and include the line to load jquery. Alternatively, as Liferay comes with AlloyUI/YUI, you can load jQuery as a module for AUI with its module yQuery
Here is a sample code using javascript\jQuery to call REST webservices inside portlet (Call Portal Service with Basic Authorization Header):
<%# include file="init.jsp"%>
$(document).on('ready',function(){
var username ="test#liferay.com";
var password ="test";
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax({
url: 'http://localhost:8080/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee/employee-id/1',
dataType: "json",
type: "get",
success: function(data){
alert(data.employeeName);
},
beforeSend: function(xhr){ xhr.setRequestHeader('Authorization',make_base_auth(username, password));
},
complete: function(){
},
error: function(){
}
});
});
</script>

how to generate api documentation [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I need to write some api documentation for a REST API that I've created. Are there tools that will stub out a nice html output similar in style to the underscore api documentation? Or perhaps something that will output something as a twitter bootstrap styled html?
I see that docco does annoated code, but I'm actually just looking to document the API only. Ideally I'd like to point a tool at the controller file and have it generate documentation about the methods and routes but not show any source code unless I specifically call out examples.
apiDoc creates a documentation from API annotations in your source code.
Integrated is an API history, with that various API version levels can be compared.
So it can be retraced what changed in the API since the last version.
Demo: http://apidocjs.com/example
Github: https://github.com/apidoc/apidoc
Check out I/O Docs on Github - http://github.com/mashery/iodocs . It's hacked in Node.js, and has a lot of community contribution/involvement. To see it working in the wild:
http://iodocs.docusign.com
http://console.datasift.com/datasift
Uber simple configuration schema (JSON), and hell, if you don't want to describe it all by hand in JSON, use I/O Doctor, a web-based tool for importing/building JSON configs with a UI:
http://iodoctor.net/
Also available on Github at https://github.com/brandonmwest/iodoctor
Let me know if I can help you get started. There are plenty of example configs in the I/O Docs repo. Take care.
I/O Docs or Swagger, which are the most popular RESTful API documentation systems. There is also RAML and Apiary.
test2doc.js helps you generate API documentation from your tests/specs. So you can always get the latest update-to-date API documents, populated with real request/response data.
Test code example:
const doc = require('test2doc')
const request = require('supertest') // We use supertest as the HTTP request library
require('should') // and use should as the assertion library
// For Koa, you should exports app.listen() or app.callback() in your app entry
const app = require('./my-express-app.js')
after(function () {
doc.emit('api-documentation.apib')
})
doc.group('Products').is(doc => {
describe('#Products', function () {
doc.action('Get all products').is(doc => {
it('should get all products', function () {
// Write specs towards your API endpoint as you would normally do
// Just decorate with some utility methods
return request(app)
.get(doc.get('/products'))
.query(doc.query({
minPrice: doc.val(10, 'Only products of which price >= this value should be returned')
}))
.expect(200)
.then(res => {
body = doc.resBody(res.body)
body.desc('List of all products')
.should.not.be.empty()
body[0].should.have.properties('id', 'name', 'price')
body[0].price.desc('Price of this product').should.be.a.Number
})
})
})
})
})

Resources