-
Notifications
You must be signed in to change notification settings - Fork 2
Topic: External API
API is short for an application programming interface. It's a web application that stores data on a local database/file; it's often referred to as API servers. On the other side of the connection, there are clients; these are systems that can request to receive the data stored on that API server, these are named API calls. In some cases, the API provider charges a premium for their data. In those cases, you can buy an API key; these keys are purchased in combination with a plan. Plans have limits on how often/many API calls you can make. Plans have rate limits for API calls; this can mean that you are limited to a fixed amount or will be charged extra if that limit is exceeded.
Protocol | Server address | API version | API key | Options |
---|---|---|---|---|
Https:// | api.server.com | /2.5/ | ?api_key={key} | ?format=json |
For our app, we had decided it would be nice to have fun programmer jokes/advice displayed on the profile page. We have used the quotes API from Stromconsultancy, it's a platform that hosts programmer related quotes that are sometimes just funny jokes or plain advice. The API is simple in its use, it is a free API and does not require an account for calls- this is especially nice for hobby or school projects. The API returns a JSON when an HTTP GET request has been made.
Protocol | Server address | Variant | Options |
---|---|---|---|
http:// | quotes.stormconsultancy.co.uk | /random | .json |
curl http://quotes.stormconsultancy.co.uk/random.json
⬇️ response
* Trying 3.217.53.122...
* TCP_NODELAY set
* Connected to quotes.stormconsultancy.co.uk (3.217.53.122) port 80 (#0)
> GET /random.json HTTP/1.1
> Host: quotes.stormconsultancy.co.uk
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Connection: keep-alive
< Content-Type: application/json; charset=utf-8
< Transfer-Encoding: chunked
< Status: 200 OK
< Cache-Control: max-age=0, private, must-revalidate
< Access-Control-Allow-Origin: *
< Date: Wed, 17 Jun 2020 11:37:12 GMT
< Vary: Accept-Encoding
< X-Request-Id: 6fc78294-203b-4afb-862a-696be458b88e
< Access-Control-Allow-Methods: GET
< X-Ua-Compatible: IE=Edge,chrome=1
< Etag: "dcfc20c6e7bdd3b260225bc85157fb3e"
< X-Runtime: 0.003659
< X-Rack-Cache: miss
< X-Powered-By: Phusion Passenger 5.0.29
< Server: nginx/1.10.1 + Phusion Passenger 5.0.29
< Via: 1.1 vegur
{"author":"Larry DeLuca","id":37,"quote":"I\u2019ve noticed lately that the paranoid fear of computers becoming intelligent and taking over the world has almost entirely disappeared from the common culture. Near as I can tell, this coincides with the release of MS-DOS.","permalink":"http://quotes.stormconsultancy.co.uk/quotes/37"}%
In the API call above, we can see that GET /random.json HTTP/1.1
signifies to a GET request, this means that we've made a request to receive data to which the API server replied HTTP/1.1 200 OK
, which means that the request is authorized. Once the server has authorized, the API call it returns the data with the header data such as date, preferences, and content type, which is as expected a JSON: Content-Type: application/JSON
.
⬇️ Deconstructing the API response
{
"author": "Larry DeLuca",
"id": 37,
"quote": "I\u2019ve noticed lately that the paranoid fear of computers becoming intelligent and taking over the world has almost entirely disappeared from the common culture. Near as I can tell, this coincides with the release of MS-DOS.",
"permalink": "http://quotes.stormconsultancy.co.uk/quotes/37"
}
There are really two ways to go about with API calls in code. You could use the built-in feature such as XMLHttpRequest()
to make HTTP GET calls (aka API calls) or use a third-party library like Axios that does the same but offers additional features such as promises or automatic JSON transformations (this is super nice).
const Http = new XMLHttpRequest();
const url = 'http://quotes.stormconsultancy.co.uk/random.json';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
if (Http.readyState == 4 && Http.status == 200) {
// do something with the data
} else {
// do something with the error
}
}
Pros: comes with javascript, easy to read, and it follows a precise order.
Cons: a lot of lines to make a simple GET request, and you still need to parse the JSON response (JSON.parse()
) to properly use it. It also may break your application if the server delays the response.
axios.get('http://quotes.stormconsultancy.co.uk/random.json').then( response => {
// do something with the data
}).catch( error => {
// do something with the error
}).then({
// always do this
})
Pros: automatically transforms JSON data. Is structured clearly, just like a switch statement—excellent handling of all outcomes. Cons: an extra package to include in your app.
For this project, we had decided to use Axios because it is feature-rich, and it has excellent error handling as well as it's automatic JSON transformer.
In the code, I had written an async function; this, of course, only works when it is pointed out what to wait for. The API call, the Axios line, has an await
expression. Once the function is executing the code, it waits for this line to fulfill the promise
which can be either fulfilled or rejected. Once ready, the code continues.
Within the code, I had chosen to utilize the session again. The returned data from the API is added to the session, and when ready (promise fulfilled), the code continues and finishes by rendering the profile page. I had decided to apply the call here rather than anywhere else because it allows for new quotes every time the profile is loaded.
/**
* Function redirects user to @see {@link get/profile}.
* @name get/homepage
* @function
* @param {string} path - Express path
* @param {callback} middleware - Express middleware
*/
router.get('/', async (req, res) => {
if (req.session.user) {
await axios.get('http://quotes.stormconsultancy.co.uk/random.json').then((response) => {
req.session.user.quote = response.data.quote;
req.session.user.author = response.data.author;
req.session.user.permalink = response.data.permalink;
}).catch( (error) => {
console.log(error);
req.session.user.quote = 'There is no right or wrong- but PHP is always wrong';
req.session.user.author = 'Dev team';
req.session.user.permalink = 'https://github.com/sjagoori/dating-app';
});
return res.render('profile', {query: req.session.user});
}
return res.render('homepage');
});