I am currently building a website that uses data from a JSON based REST API. I need to retrieve a JSON file from a specific URL but I am struggling with how to access it because the API requires a username and password.
I have a javascript variable containing the url that I need to get the data from, as well as the correct username and password. I just dont know how to put it all together to make a request.
–
Alternatively, I have managed to find a php class that very easily and simply returns PHP arrays for all the data i need. I simply append my username and password inside a php file and the class takes care of the rest. This maybe an easier way to access the JSON rather than using javascript? However I have no idea how I can pass a javascript URL variable into it.
Thanks a lot for your help. I hope i’ve made my problem clear!
I’m assuming that the REST API is using basic access authentication as the authentication mechanism. You can read from the article that all it takes is to properly set the
Authorizationrequest header and here’s an example of how you can do it in JavaScript with jQuery.It’s a very simple authentication scheme and one of it’s implications is that you would have to supply the user’s client with the username and password that can be easily decoded back to plain text. Considering that most terms of services prohibit you from disclosing your access credentials, you’ll probably want to either retrieve the data in PHP or expose a REST interface in PHP that proxies the requests to the actual API, unless you’re using the JS client for personal purposes only.