3

I have some web services, written in node js and express. I want to use api key based service. Suppose I currently have a web service "getRooms".

app.get('/getRooms/', function (req, res) {
    'use strict';
    N.API.getRooms(function (rooms) {
        res.send(rooms);
    },function (err) {
        res.send(err);
    });
});

I am using it by calling https://xxxxxx/getRooms. Now I want to use https://xxxxxx/APIKEY/getRooms. This APIKEY is different for different clients. So how do I modify my web services to achieve this?

2 Answers 2

4

You can modify it as /APIKEY/getrooms to achieve the desired result. However it would be better it you send APIKEY in request header but obviously it depends on your case.

5
  • can you please explain what is route at /xxxxx. so that I can post
    – Bobby
    May 18, 2016 at 5:10
  • I have edited the answer check. you simply have to put APIKEY before /getrooms/ May 18, 2016 at 5:12
  • api keys will be different, which are _id from mongodb. then how do I define APIKEY statically
    – Bobby
    May 18, 2016 at 5:16
  • you can use a param then /:apikey/getrooms. So the request will be like : /c822c1b63853ed273b89687ac505f9fa/getrooms. /123456789/getrooms. /getrooms will result in 404. May 18, 2016 at 5:22
  • Yes this is what I wanted. let me try first. :)
    – Bobby
    May 18, 2016 at 5:26
0

you can modify your code like this

app.get('/getRooms?api_key=xxxx', function (req, res) {
    console.log(req.query.api_key) // print xxxx when user request to https://xxxxxx/getRooms/APIKEY
});
3
  • I've thought of this procedure, but if I already have a parameter for that web service? like app.get('/getRoom/:room', function (req, res) {})
    – Bobby
    May 18, 2016 at 5:12
  • 1
    so you need setup to user send request with api_key in headers. Then in server side you can get user api key with req.headers['api_key']
    – KibGzr
    May 18, 2016 at 5:16
  • Putting in header is a good approach when it will be called from code. For GET services, if we hit it in URL, then header part won't work.
    – Bobby
    May 18, 2016 at 5:19

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.