Using an API with JavaScript (A Beginners Guide to API)

Using an API with JavaScript (A Beginners Guide to API)

If you are faced with the task of accessing the API in your JavaScript application and don’t know where to start, this article will help you figure it out quickly.

How To Use an API with JavaScript (The Complete Beginner's Guide) Get an API key. Test the API Endpoints. Make your first app with API. If you are faced with the task of accessing the API in your JavaScript application and don’t know where to start, this article will help you figure it out quickly.

What is REST API (from a JavaScript perspective)?

To begin, let us define what is hidden under the API abbreviation. API (Application Programming Interface) can be considered as a set of rules that are shared by a particular service. These rules determine in which format and with which command set your application can access the service, as well as what data this service can return in a response. API acts as a layer between your application and external service.

REST API (Representational state transfer) is an API that uses HTTP requests for communication with web services and must comply with certain constraints. Full constraints list can be viewed at the link. Here are some of them:

  1. Client-server architecture – the client is responsible for the user interface, and the server is responsible for the backend and data storage. Client and server are independent of each other, and each of them can be replaced separately.
  2. Stateless – no data from the client is stored on the server-side. The session state is stored on the client-side.
  3. Cacheable – clients can cache server responses to improve performance.

From the JavaScript side, the REST API integration can be viewed as a connection to a data source located at a specific address on the Internet, which can be accessed in a certain way through certain libraries.

Prerequisites

We will try to keep things simple, so to work with queries we will use the axios library because of its simplicity and universality. Also, in order to understand what the article is about, you will need some basic knowledge of HTML and CSS and JavaScript syntax and datatypes.

CRUD and types of requests

CRUD is a programming concept denoting four basic actions (create, read, update, and delete) that can be performed on a data source. In a REST API, these actions correspond to Types of Requests or Request Methods:

  • POST: Create action. Adds new data to the server. Using this type of request, you can, for example, add a new ticket to your inventory.
  • GET: Read action. Retrieves information (like a list of items). This is the most common type of request. Using it, we can get the data we are interested in from those that the API is ready to share.
  • PUT: Update action. Changes existing information. For example, using this type of request, it would be possible to change the color or value of an existing product.
  • DELETE: Delete action. Deletes existing information.
Endpoints and CRUD

In order to work with REST APIs, it is important to understand the Endpoint concept. Usually, Endpoint is a specific address (for example, https://hotels-to-stay.com/best-hotels-paris), by referring to which (with certain request method) you get access to certain features/data (in our case – the list of best hotels in Paris). Commonly, the name (address) of the endpoint corresponds to the functionality it provides.

To learn more about endpoints and CRUD, we will look at simple API example within the RapidAPI service. This service is an API Hub providing the ability to access thousands of different APIs. Another advantage of RapidAPI is that you can access endpoints and test the work of the API directly in its section within the RapidAPI service.

We will go through the JAAS – JSON as a service. This API is used to generate and modify JSON objects, that is useful in coding practice.

In order to find JAAS API section, enter its name in the search box in the RapidAPI service or go to the “Data” category from “All Categories” list and select this API from the list. JAAS API through RapidAPI is free, so you can create as many JSON objects as you want.

Once you select JAAS API, the first page you’ll see is the API Endpoints subsection. This includes most of the information needed to get started.

We will go through all CRUD actions: create, read, update, delete. For each of these actions, JAAS API provides a corresponding endpoint.

In order to demonstrate the entire CRUD functionality in JavaScript, we will complete the following steps:

  1. Make a POST request for the API used to create the object. We will save object id which was received in the answer.
  2. Make a GET request where we will use the id from the first step, thereby demonstrating GET requests and the fact that the object was created
  3. Make a PUT request where we substitute the modified object and demonstrate the answer.
  4. Make a DELETE request with the object id and show the answer.
  5. Make a GET request with id again to show that the DELETE method worked and the object is definitely not there.

1. So, let’s begin. Firstly we need to connect the axios library to our html file for easy work with queries.

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Create a constant with an API address within the RapidAPI service.

// Constant URL value for JAAS API
const RAPIDAPI_API_URL = 'https://arjunkomath-jaas-json-as-a-service-v1.p.rapidapi.com/';

Next, we create an object/dictionary with constant headers for RapidAPI, which are required during accessing. Since these headers will be in each request, they also need to be put into a separate variable.

// Object with RapidAPI authorization headers and Content-Type header
const RAPIDAPI_REQUEST_HEADERS = {
  'X-RapidAPI-Host': 'arjunkomath-jaas-json-as-a-service-v1.p.rapidapi.com'
  , 'X-RapidAPI-Key': '7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  , 'Content-Type': 'application/json'
};

We create an object on which we will work (send in requests, modify) and a variable to store id.

// Variable to store ID
let STUDENT_ID = '';

// Object for examples
const student = {
  name: 'John'
  , surname: 'Doe'
  , age: 18
};

Now we will start the direct implementation of the first step from the list. We will make a POST request to the specified address with the object and headers. That is, here we create a student object on the server.

// Making a POST request using an axios instance from a connected library
axios.post(RAPIDAPI_API_URL, student, { headers: RAPIDAPI_REQUEST_HEADERS })
  // Handle a successful response from the server
  .then(response => {
    	    // Getting a data object from response that contains the necessary data from the server
    	    const data = response.data;
    	    console.log('data', data);

    	    // Save the unique id that the server gives to our object
    	    STUDENT_ID = data._id;
  })
  // Catch and print errors if any
  .catch(error => console.error('On create student error', error));

In the first parameter, we send the URL to the function. The second parameter is the data. The third parameter is the object with the headers for the request. Then we either get a successful response and output it to the browser console, or the request ends with an error and we also display it in the console.
The response object contains many fields, but we are interested in the data field.
As a result, in the console we get the following JSON output:

{
  "_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
  "created_at": 1563051939620,
  "body": {
  "name": "John",
  "surname": "Doe",
  "age": 18
  }
}

Now we have the variable STUDENT_ID containing the following line:

"3060e599-b758-44cc-9eb4-8fda050b76d2"

2. Let’s test a GET request.

// Making a GET request using an axios instance from a connected library
axios.get(`${RAPIDAPI_API_URL}/${STUDENT_ID}`, { headers: RAPIDAPI_REQUEST_HEADERS })
  .then(response => {
    	    console.log(response.data);
  })
  .catch(error => console.error('On get student error', error))

The first parameter is the union of the API URL and the id of the object that we want to receive. The second parameter is the necessary headers. Everything else as in the previous example.

As a result, we will see the following in the console:

{
  "_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
  "body": {
  "name": "John",
  "surname": "Doe",
  "age": 18
  },
  "created_at": 1563051939620
}

Everything works as expected. Let’s proceed.

3. Now we are testing a PUT request, that is, trying to modify an object created earlier on the server.

Imagine a situation where someone entered incorrect data, and our student John is not 18, but 20 years old. We will also need to keep his average score. To do this, we modify our object as follows:

student.age = 20;
student.score = 4.0;

Now John is 20, his average score is 4.0, and the student object now looks like this:

{
  "name": "John",
  "surname": "Doe",
  "age": 20,
  "score": 4
}

We need to inform the server about this information and for this task we use the following code snippet:

axios.put(`${RAPIDAPI_API_URL}/${STUDENT_ID}`, student, { headers: RAPIDAPI_REQUEST_HEADERS })
    	.then(response => {
          console.log(response.data);
    	})
    	.catch(error => console.error('On change student error', error))

That is, we execute a PUT request, where the first parameter is the URL pointer to the desired object, the second parameter is the already updated student, and the third is the necessary headers.

As a result, after executing the code, we have the following response from the server:

{
  "_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
  "body": {
  "name": "John",
  "surname": "Doe",
  "age": 20,
  "score": 4
  }
}

_id is correct, data is updated.

4. Now we are testing the DELETE method, that is, deleting an object. In order to delete an object, simply execute the following code:

axios.delete(`${RAPIDAPI_API_URL}/${student.id}`, { headers: RAPIDAPI_REQUEST_HEADERS })
    	.then(response => {
        	console.log(response.data);
    	})
    	.catch(error => console.error('On change student error', error))

Parameters are specified as in the previous examples. The result is as follows:

{
  "_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
  "message": "Data Deleted"
}

We got a message saying that our object is deleted.

5. Great, but let’s see what happens if we try to retrieve the deleted object using the GET request:

// Making a GET request using an axios instance from a connected library
axios.get(`${RAPIDAPI_API_URL}/${STUDENT_ID}`, { headers: RAPIDAPI_REQUEST_HEADERS })
  .then(response => {
    	    console.log(response.data);
  })
  .catch(error => console.error('On get student error', error))

We received the answer that this object no longer exists. Everything works as we expected.

{
  "errors": [
  "Item not found"
  ]
}
How To Connect to an API (with JavaScript)

Now we know the basic elements of working with API in JavaScript, and we can create a step-by-step guide to creating a JavaScript app with API integration:

1. Get an API key

An API key is usually a unique string of letters and numbers. In order to start working with most APIs, you must identify yourself (register) and get an API key. You will need to add an API key to each request so that the API can recognize you. On the example of RapidAPI – you can choose the method of registration that will be convenient for you. This can be a username, email, and password; Google, Facebook or Github account.

2. Test API Endpoints with JavaScript

After we receive the API key, we can make a request to API endpoints (according to the rules in the documentation) to check if everything works as we expected. In the case of working with RapidAPI, immediately after registering with the service, we can go to the section of the API of our interest, subscribe to it and test endpoints directly on the API page. Next, we can quickly create a JavaScript snippet using the axios library with requests to the desired endpoint and test its work in the browser console.

3. Make your first JavaScript app with API

After we check the endpoints, we can start creating an application, including the necessary API calls.

Example: How to Build a ‘Comment Sentiment Analyzer’ App (with APIs & JavaScript)

Now, let’s apply what we learned above and create a small service for analyzing the sentiment of user comments.

Let’s imagine that we have created such a bright product that causes such a strong reaction from users that they cannot hold back emotions when they write comments. To help our users determine the nature of their feelings about the product, we will expand the usual commenting form and add functionality to analyze the sentiments of their comments.

In this task, we will be helped by Text-Processing API, which is available through the RapidAPI service. This API works under freemium conditions, allowing a limited number of texts per day to be processed for free. Since we are going to process just a few comments for test purposes, that’s enough for us.

To send requests, we will continue to use the axios library. You will also need the qs library to encode requests.

1. Get an API key

After registering with RapidAPI service, we will receive a service key, and this will be enough for us to start work with the Text-Processing API. You can register by clicking on the ’Sign Up’ button on RapidAPI menu.

As mentioned earlier, you can register in any convenient way:

2. Test the API Endpoints

To analyze the sentiment of user comments, we need the sentiment endpoint. We will test it directly in the browser by sending a negative test comment.

As we can see, API returns JSON with a negative assessment, so apparently, everything works as it should.

3. Make your first app with API

Now we will create our small application for analyzing the sentiment of comments.

The project structure consists of three files: index.html, style.css, text-processing.js

  1. index.html – our HTML template
  2. style.css – styles for the HTML file
  3. text-processing.js – JavaScript logic file

Firstly, we need the index.html in which everything will be displayed:

Let’s break it down:

First, we need to connect our styles in the project:

<!-- Import our css styles -->
<link rel="stylesheet" href="styles.css">

Then, we’ll connect to the axios library for requests:

<!-- Import axios library -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

And also the qs library to transform data before sending:

<!-- Querystring library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.7.0/qs.min.js"></script>

And then our own JS script to tie it together:

<!-- Import our javascript file -->
<script src="text-processing.js"></script>

and here it is all together (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Text Processing</title>

  <!-- Import our css styles -->
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="main">
    	<h2 class="main-header">Comment text analysys</h2>
    	<section class="main-input-comment">
        	<label for="comment">Write your comment here:</label>
        	<textarea
                	name="comment"
                	id="comment"
                	class="main-comment-area"
                	placeholder="Your comment..."
        	>
        	</textarea>
        	<button class="main-analyze-button" onclick="onAnalyzeButtonClick()">Analyze...</button>
    	</section>
    	<section class="main-result">
        	<p id="main-result-block" class="main-result-block invisible">
            	<span>Result:</span>
            	<span id="result"></span>
        	</p>
    	</section>
  </div>

  <!-- Import axios library -->
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <!-- Querystring library -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.7.0/qs.min.js"></script>
  <!-- Import our javascript file -->
  <script src="text-processing.js"></script>
</body>

Next, let’s create some simple styling for the style.css file:

* {
  font-family: "Arial", Arial, sans-serif;
  font-weight: 400;
  padding: 0;ь
  margin: 0;
  border: 0;
}
body {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
label, textarea {
  display: block;
}
.main {
  padding: 10px;
  width: 35%;
  box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
.main-header {
  text-align: center;
  margin-bottom: 20px;
}
.main-input-comment { margin-bottom: 20px; }
.main-comment-area {
  width: 95%;
  border: #ced4da 1px solid;
  border-radius: 10px;
  resize: none;
  padding: 10px;
  margin-bottom: 10px;
  font-size: 16px;
}
.main-analyze-button {
  width: 100%;
  padding: 5px;
  border: 1px solid #007bff;
  background-color: #007bff;
  border-radius: 7px;
  color: white;
  text-align: center;
  font-size: 16px;
  outline: none;
}
.main-analyze-button::-moz-focus-inner {border: 0;}
.main-analyze-button:hover {
  background-color: #0069d9;
  border-color: #0069d9;
  cursor: pointer;
}
.main-result-block { text-align: center; }
.pos { color: green; }
.neg { color: darkred; }
.neutral { color: gray }

.invisible { display: none; }

And finally, let’s create our JavaScript file (text-processing.js):

To begin with, let’s write constants such as the request URL and request headers (as we did before):

// Text-Processing API Url
const API_URL = 'https://japerk-text-processing.p.rapidapi.com/sentiment/';

// RapidAPI request headers
const REQUEST_HEADERS = {
  'X-RapidAPI-Host': 'japerk-text-processing.p.rapidapi.com'
  , 'X-RapidAPI-Key': '7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  , 'Content-Type': 'application/x-www-form-urlencoded'
};

Now we create a request based on the text entered by the user:

const analyzeComment = (comment, callback) => {
  // Creating an object to send to the server
  const data = {
    	    text: comment
    	    , language: 'english'
  };
  // Encoding data for application/x-www-form-urlencoded content type
  const formattedData = Qs.stringify(data);
  // POST request to server
  axios.post(API_URL, formattedData, { headers: REQUEST_HEADERS })
    	    .then(response => {
             const data = response.data;
        	  // Calling a callback function with data from the server
        	  callback(data)
    	    })
    	    .catch(error => console.error(error))
};

Here comment is the text that the user entered, and callback is a function that will do something with the response from the server in the future.

In the beginning, we created the data object based on the API documentation. Then we translated this object into a special format application/x-www-form-urlencoded using the Qs library.

As a result, we will need to make a request like in the previous examples:

  • get the result
  • call the callback function
  • and send to it a response from the server

Now we need a function that we can pass as a callback to the previous one, that is, a function that does something with the result, namely, it displays it to the user.

const displayResult = result => {
  // Remove invisible class for main-result-block
  const resultBlockElement = document.getElementById('main-result-block');
  resultBlockElement.classList.remove('invisible');

  // Setting the color of the result text depending on the response label
  const label = result.label;
  const resultElement = document.getElementById('result');
  resultElement.setAttribute('class', label);
  let resultText = '';

  // Choosing the result text depending on response label
  switch (label) {
    	case 'pos':
        	resultText = 'Wow! Your comment is very positive!';
        	break;
    	case 'neg':
        	resultText = 'Negative comment =(';
        	break;
    	case 'neutral':
        	resultText = 'Simple comment =)';
        	break;
    	default:
        	resultText = 'Hmmm, can't understand your comment';
  }

  // Setting the result text
  resultElement.textContent = resultText;
};

Perhaps we also need a function that will do something if the user has not entered anything and pressed the button. Here we make the result block invisible by applying the class invisible to it and display the message.

const handleEmptyComment = () => {
  const resultBlockElement = document.getElementById('main-result-block');
  resultBlockElement.classList.add('invisible');
  return alert('Your comment is empty =(');
};

We also need to create a handler function that will work when a button is pressed and combine everything we wrote before:

// Button click handler
const onAnalyzeButtonClick = () => {
  // Getting a textarea element with a comment
  const commentElement = document.getElementById('comment');
  // Getting comment text
  const commentText = commentElement.value.trim();

  // Handle empty comment
  if (!commentText) {
    	    return handleEmptyComment();
  }
  // Calling the API and passing the result with the displayResult as a callback function
  return analyzeComment(commentText, displayResult);
};

Finally, we get the following file:

// Text-Processing API Url
const API_URL = 'https://japerk-text-processing.p.rapidapi.com/sentiment/';

// RapidAPI request headers
const REQUEST_HEADERS = {
  'X-RapidAPI-Host': 'japerk-text-processing.p.rapidapi.com'
  , 'X-RapidAPI-Key': '768d224b32mshbe5f76705cbfd9bp154850jsnba7a2201e140'
  , 'Content-Type': 'application/x-www-form-urlencoded'
};

// Button click handler
const onAnalyzeButtonClick = () => {
  // Getting a textarea element with a comment
  const commentElement = document.getElementById('comment');
  // Getting comment text
  const commentText = commentElement.value.trim();

  // Handle empty comment
  if (!commentText) {
    	    return handleEmptyComment();
  }
  // Calling the API and passing the result with the displayResult as a callback function
  return analyzeComment(commentText, displayResult);
};

const analyzeComment = (comment, callback) => {
  // Creating an object to send to the server
  const data = {
    	    text: comment
    	    , language: 'english'
  };
  // Encoding data for application/x-www-form-urlencoded content type
  const formattedData = Qs.stringify(data);
  // POST request to server
  axios.post(API_URL, formattedData, { headers: REQUEST_HEADERS })
    	    .then(response => {
        	  const data = response.data;
        	  // Calling a callback function with data from the server
        	  callback(data)
    	    })
    	    .catch(error => console.error(error))
};

const handleEmptyComment = () => {
  const resultBlockElement = document.getElementById('main-result-block');
  resultBlockElement.classList.add('invisible');
  return alert('Your comment is empty =(');
};

const displayResult = result => {
  // Remove invisible class for main-result-block
  const resultBlockElement = document.getElementById('main-result-block');
  resultBlockElement.classList.remove('invisible');

  // Setting the color of the result text depending on the response label
  const label = result.label;
  const resultElement = document.getElementById('result');
  resultElement.setAttribute('class', label);
  let resultText = '';

  // Choosing the result text depending on response label
  switch (label) {
    	case 'pos':
        	resultText = 'Wow! Your comment is very positive!';
        	break;
    	case 'neg':
        	resultText = 'Negative comment =(';
        	break;
    	case 'neutral':
        	resultText = 'Simple comment =)';
        	break;
    	default:
        	resultText = 'Hmmm, can't understand your comment';
  }

  // Setting the result text
  resultElement.textContent = resultText;
};

Our click handler (onAnalyzeButtonClick) is added to the button.

<button class="main-analyze-button" onclick="onAnalyzeButtonClick()">Analyze...</button>

The app is ready! We have implemented Anger Management with Javascript, and now every user will be able to understand what emotions their comments express:

You may also like: What the difference between REST API and RESTful API?.

Conclusion

In this article, we explored the possibilities of JavaScript when working with the REST API, studied the concept of CRUD and its implementation using JavaScript, and also created our own application that has the capabilities of AI text sentiment analysis.

Thank you for reading ! Please share if you liked it!

APIs for Beginners - What is an API? How to use an API?

APIs for Beginners - What is an API? How to use an API?

APIs for Beginners, What exactly is an API? How do you use an API? Learn all about APIs in this full course for beginners. Learn how to use Postman and helper libraries in both JavaScript and Python. Lean how to create a project using an API using both Node.js and Flask. Learn what APIs do, why APIs exist, and the many benefits of APIs. Explore APIs online

APIs for Beginners - What is an API? How do you use an API? Learn all about APIs (Application Programming Interfaces) in this full course for beginners. You will learn what APIs do, why APIs exist, and the many benefits of APIs. APIs are used all the time in programming and web development so it is important to understand how to use them.

You will also get hands-on experience with a few popular web APIs. As long as you know the absolute basics of coding and the web, you'll have no problem following along.

⭐️ Course Contents ⭐️

⭐️ Unit 1 - What is an API
⌨️ Video 1 - Welcome (0:00:00)
⌨️ Video 2 - Defining Interface (0:03:57)
⌨️ Video 3 - Defining API (0:07:51)
⌨️ Video 4 - Remote APIs (0:12:55)
⌨️ Video 5 - How the web works (0:17:04)
⌨️ Video 6 - RESTful API Constraint Scavenger Hunt (0:22:00)

⭐️ Unit 2 - Exploring APIs
⌨️ Video 1 - Exploring an API online (0:27:36)
⌨️ Video 2 - Using an API from the command line (0:44:30)
⌨️ Video 3 - Using Postman to explore APIs (0:53:56)
⌨️ Video 4 - Please please Mr. Postman (1:03:33)
⌨️ Video 5 - Using Helper Libraries (JavaScript) (1:14:41)
⌨️ Video 6 - Using Helper Libraries (Python) (1:24:40)

⭐️ Unit 3 - Using APIs
⌨️ Video 1 - Introducing the project (1:34:18)
⌨️ Video 2 - Flask app (1:36:07)
⌨️ Video 3 - Dealing with API Limits (1:50:00)
⌨️ Video 4 - JavaScript Single Page Application (1:54:27)
⌨️ Video 5 - Moar JavaScript and Recap (2:07:53)
⌨️ Video 6 - Review (2:18:03)

Designing API Methods in JavaScript

Designing API Methods in JavaScript

Designing API methods in JavaScript is a very useful skill to learn and allows you to look at programming in a different perspective...

Originally published by Christopher T  at jsmanifest.com

A perspective whereas instead of building a project for your users, you're building a project for developers to use. And if you haven't built a library or an SDK before, this article may help you gain an understanding of where and how to start beginning with method design.

JavaScript is a loosely typed language which we as developers can take advantage of to create robust, multi-use APIs.

This article will go over a couple of rules to keep in mind when designing methods for an API in JavaScript.

1. Named Parameters

The first one we are going to talk about is named parameters. Back in the old days before ES6 was introduced, the only way to declare functions were function declarations using the function syntax. To determine where to go with execution flows, you would take a function arity (the number of arguments the function expects), convert it to an array and apply the rest of the logic depending on how the arguments look like.

In this example, the animaloptions, and callback are the parameters to the function and the arity will be three. The function is designed to create a new account, and each account will have some default settings if it wasn't provided by the caller:

function createAccount(
  username = '',
  password = '',
  nickname = '',
  email = '',
  gender = 'Male',
  bio = '',
  subscription = 'Basic',
  callback,
) {
  if (!username || !password || !email) {
    throw new Error(
      'You are missing one or all of the following fields: "username", "password", "email"',
    )
  }
  return api
    .createAccount({
      username,
      password,
      nickname,
      email,
      gender,
      bio,
      subscription,
    })
    .then((result) => {
      if (callback) callback(null, result)
    })
    .catch((error) => {
      console.error(error)
      if (callback) callback(error)
    })
}

createAccount(
'lucas',
'applebee123x123',
'',
'[email protected]',
'',
'My bio',
'Basic',
function cb(err, data) {
if (err) {
console.error(err)
}
// do something with data
},
)

The problem with this is that the caller has to know the exact order of arguments to pass in as the parameters to the function in order to function properly even if one or more parameters weren't required. It can be difficult to memorize the requirements in order while it can be very easy to mess up the order if you aren't careful. In addition, it doesn't really make much sense to make a parameter required if it isn't required to make the function do its work properly.

It will also be difficult to maintain in the future because when you or your boss needs to get rid of username and make it email as the new username instead, you would have to change the logic around.

A better practice is to simply use an object:

function createAccount({
username = '',
password = '',
nickname = '',
email = '',
gender = 'Male',
bio = '',
subscription = 'Basic',
callback,
}) {
if (!username || !password || !email) {
throw new Error(
'You are missing one or all of the following fields: "username", "password", "email"',
)
}
return api
.createAccount({
username,
password,
nickname,
email,
gender,
bio,
subscription,
})
.then((result) => {
if (callback) callback(null, result)
})
.catch((error) => {
console.error(error)
if (callback) callback(error)
})
}

We benefit from readability as well as more control over maintainability as you only need to remove the username from the code:

function createAccount({
password = '',
nickname = '',
email = '',
gender = 'Male',
bio = '',
subscription = 'Basic',
callback,
}) {
if (!password || !email) {
throw new Error(
'You are missing one or all of the following fields: "email", "password"',
)
}
return api
.createAccount({
password,
nickname,
email,
gender,
bio,
subscription,
})
.then((result) => {
if (callback) callback(null, result)
})
.catch((error) => {
console.error(error)
if (callback) callback(error)
})
}

Making the call also becomes more terse and readable:

createAccount({
password: 'applebee123x123',
email: '[email protected]',
bio: 'My bio',
callback: function cb(err, data) {
if (err) {
console.error(err)
}
// do something with data
},
})
2. Method Chaining / Fluent API

My favorite way of writing APIs is using the fluent API by method chaining.

Method chaining is simply the process of chaining multiple calls one after the other. The general idea is to achieve a readable and fluent code, thus making it quicker to understand. These methods are commonly verbs (like rotate)

For example:

getPhoto('../nemo_the_fish.jpg')
.applyFilter('grayscale', '100%')
.rotate(100)
.scale(1.5)

This translates to: "retrieve the image nemothefish.jpg and apply the grayscale filter with a value of 100%, rotate the image by 100 degrees and increase the scale by 1.5 times more."

A good thing about this practice is that it's very quick to get started with writing your own fluent API interface. You would simply return the reference to the context inside your method calls so that it can be chained:

const createWarrior = function createWarrior(name) {
let hp = 100
let battleCryInterval = 0

return {
bash: function(target) {
target -= 10
return this
},
// Increase the wrarior's health by 60, decrementing it by 1 every second for 60 seconds
battleCry: function battleCry() {
hp += 60
battleCryInterval = setInterval(() => {
hp -= 1
}, 1000)
setTimeout(() => {
if (battleCryInterval) {
clearInterval(battleCryInterval)
}
}, 60000)
return this
},
getHp: function getHp() {
return hp
},
}
}

const warrior = createWarrior('chris')
const otherWarrior = createWarrior('bob')

warrior
.battleCry()
.bash(otherWarrior)
.bash(otherWarrior)
.bash(otherWarrior)
.bash(otherWarrior)
.bash(otherWarrior)

const otherWarriorsHp = otherWarrior.getHp()

console.log(otherWarriorsHp) // result: 100

One of the greatest examples of a fluent API is jQuery, and thanks to the library's fluency it arguably makes it one of the easiest JavaScript libraries to both learn and use:

$(window).resize(function() {
$('#logbox').append('<div>The window resized</div>')
})

However, the method chaining fluent API comes with a few drawbacks.

The biggest drawback is that it can be difficult to set a breakpoint in the middle of a chain, making errors difficult to debug. In addition, it encourages too much procedural code. There are ways to get around the debugging issue though by inserting loggers at any step in the chain and using them to call subsequent methods with it.

Another drawback is that you can get caught up in the act of writing long sentences with tight dot notation access. This can get in the way of keeping things simple, so remember to keep things simple.

3. Function Polymorphism

You might have heard of the term polymorphism in other languages, generally where something behaves differently based on the context.

The same concept applies in function polymorphism in JavaScript. These are functions that behave accordingly to the arguments passed in (which is our context).

APIs often gather arguments to an array or array-like structure in order to have more control over them. Having them into an array structure allows them to do things like pass them into other functions in the same scope and vice versa.

Before arrow functions were introduced, the common practice to gather arguments inside polymorphic functions was using the array-like arguments object. Sometimes you might be in situations where you need to do more things with the arguments after you assigned them to an array. Even though arguments is an array-like object, it doesn't really function like a real array because it is missing essential array functions--and this is very limiting.

The way developers get around that is to make a separate, shallow copy by using Array.prototype.slice.call(). This is called method delegation. In order words, you delegate the slice() call to the Array.prototype object.

An example of this would look like this:

const args = Array.prototype.slice.call(arguments, 0)


This will copy the items starting at index 0 and return everything onwards.

Arguments doesn't have real methods like .push or .shift, so we convert it to an array with Array.prototype.slice so that we can get access to all of the array methods.

In ES6, we can easily convert it to an array by using the spread operator as shown below:

const someFunction = function(...args) {
console.log(args)
console.log(args.shift())
}

someFunction(1, 'hello', 'bob')
// result:
// [1, "hello", "bob"]
// 1

When you have your arguments into an array or array-like structure, you can determine where to go with the execution logic based on how the arguments look like. This makes it very flexible to be used for multiple purposes without writing too much code.

Without spreading:

const applyFilter = function(filter, value, options) => {
const args = [].slice.call(arguments, 0)
console.log(args.length) // result: 2
}

applyFilter('grayscale', '100%')

With spreading:

const applyFilter = (...args) => {
console.log(args.length) // result: 1
}

applyFilter('grayscale', '100%')

With this in mind, we can now determine how to handle the execution from these arguments:

const applyFilterToImage = (image) => {
return function applyFilter(...args) => {
// we can also grab args with [].prototype.slice.call(arguments, 0)

let options
let filters = {}
let callback

const arg1 = args[0]
// The caller wants to apply multiple filters
if (args.length === 1) {
  if (arg1 &amp;&amp; typeof arg1 === 'object') {
    filters = { ...arg1 }
    // Find out of the caller wants the new image with applied filters back by checking if a callback was passed in
    const arg2 = args[1]
    if (arg2 &amp;&amp; typeof arg2 === 'function') {
      callback = arg2
    }
  } else {
    throw new Error(
      'You must supply an object if you are only providing the first argument',
    )
  }
} else {
  if (args.length &gt; 2) {
    // The caller passed in options as the third argument
    if (typeof args[3] === 'object') {
      options = args[3]
    }
      // The caller provided a callback function and wants the image with applied filters passed back
    else if (typeof args[3] === 'function') {
      callback = args[3]
    }
  }
  // The caller wants to apply one filter
  if (typeof arg1 === 'string') {
    const filter = arg1
    const value = args[1]
    filters[filter] = value // or filters = { [filter]: value }
  } else {
    if (callback) {
      callback(new Error('Filter is not a string'))
    }
  }
}
  const newImg = api.filterImage(filters, options)
  if (callback) {
    return callback(null, newImg)
  }

}
}

const img = '../bob_the_builder.jpg'
const applyFilter = applyFilterToImage(img)
const callback = (newImg) => {
console.log(newImg)
}

applyFilter({
grayscale: '100%',
rotate: 100,
scale: 1.5,
}, callback)

The simple function allows the developer to use it in multiple ways:

  1. Apply a single filter by providing a string and a value as the first and second argument.
  2. Or apply multiple filters by providing an object of key/value pairs as the first argument.
  3. Or apply a single filter by providing an object of one filter key/value as the first argument.
  4. Optionally receive the newly filtered image back through a callback as the second or third argument (position depends on what they passed in for the filters.)
Conclusion

That concludes the end of this article. Look out for more posts from me in the future!

Originally published by Christopher T  at jsmanifest.com

===========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Svelte.js - The Complete Guide

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ JavaScript: Coding Challenges Bootcamp - 2019

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

How to do basic Animations with HTML5 Canvas Element and JavaScript API

How to do basic Animations with HTML5 Canvas Element and JavaScript API

In this Canvas crash course, you'll learn how to do basic animations with HTML5 Canvas Element and JavaScript API. We will look at the HTML5 Canvas element and JavaScript API to draw shapes, paths and do some basic animation. <canvas> is an HTML element that allows a user to create graphics using JavaScript. To start a canvas project, we will need an HTML file and a Javascript file. Using JavaScript to control <canvas> elements, it's also very easy to make (interactive) animations

Canvas Crash Course

Learn how to do basic Animations with HTML5 Canvas Element and JavaScript API

In this video we will look at the HTML5 Canvas element and JavaScript API to draw shapes, paths and do some basic animation

  • Intro - 0:20
  • Create Context - 2:05
  • Rectangles (fillRect, strokeRect, etc) - 4:03
  • Paths (moveTo, lineTo) - 9:41
  • Arcs / Circles - 16:15
  • Bezier Curves - 26:18
  • Bounce Animation - 28:45
  • Character Animation - 40:25

GitHub: https://codepen.io/bradtraversy/pen/YzPeNxg