Build your own Shakespeare Translation Web App with JavaScript Fetch API
Tags: javascript, webdev, codenewbie, tutorial
Published: 2021-04-10 20:50:54

Shakespeare may have been a genius, but one thing's for sure: he wasn't speaking our language. His ever-popular works (dramas and poems) make his unique language style live even today.
I've always been curious about how Shakespeare would've expressed my thoughts in his words. _Have you been too??_
**Then you've come to the right place, my friend!**

This is a vanillaJS project which uses API from https://funtranslations.com/ to **translate English text into Shakespeare English.**

| Prerequisites        | Basic understanding of HTML and CSS, an understanding of what JavaScript is.           |
| ------------- |:-------------:|

This is what we'll build:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/85qojwxr74iiajwgrumb.PNG)

>Try out the app [here](https://iamshakespeare.netlify.app/)

##Source Code
In case you get lost while following along, you can grab the [source code from here](https://github.com/nayyyhaa/shakespeare-translator).

Let's begin!

## Getting Started
To get started, we'll be using VSCode for writing our code. Create your first file with the name **index.html** for writing out HTML code.
In our Application, we have 3 basic elements:
1. Input Field - to accept the user's input
2. Translate Button - to create an event when the user clicks on the translate button.
3. Output Field - to preview the translated text.

These 3 elements can be created as follows in HTML:
###### HTML code snippet - index.html
```html
<body>
    <input type="textarea" id="inputTxt" placeholder="insert your text">
    <button id="translateButton">Translate!</button>
    <p id="outputTxt"></p>
    <script src='/scripts/app.js'></script>
</body>
```

> _Note: < script > tag is being used to bind this HTML file with the JavaScript file **app.js**._

## Initialising variables to store our data
This section of the code sets up the variables we need to store the data our program will use.
In your **app.js** file, create the following variables:
###### JS code snippet - app.js 
```js
let inputElement = document.querySelector("#inputTxt"); // input element
let translateBtnElement = document.querySelector("#translateButton"); // button element
let outputElement = document.querySelector("#outputTxt"); // output element
let url="https://shakespeare.p.mashape.com/shakespeare.json"; //API URL
```
The first three variables `inputElement`, `translateBtnElement`, `outputElement` are each made to store a reference to the form text input, translate button and output element in our HTML.
Our final variable `url` is used to store the server's API call URL from where we obtain the translated data.

Here, we've used `.querySelector()` function for selecting the particular **id** that we've already set in our index.html file.

To listen to the button click event we need to define an event handler function.
```js
translateBtnElement.addEventListener("click", translateFunction);
```
Here,
-    `click` - is the event
-    `translateBtnElement` - is the event listener
-    `translateFunction` - is the event handler/callback function.

After `click` event has been fired on `translateBtnElement`, the  `addEventListener()` method handles by calling `translateFunction()`.

Before defining the `translateFunction()` we need to get some basic knowledge about APIs.

###What is an API?

API stands for **Application Programming Interface**, is a set of functions that allows applications to access data and interact with external software components, operating systems, or microservices.

_WOAH! What?!_

OK! Let me explain this to you in easy words. Suppose you are in a restaurant and you are dying to have that chocolate cake. You don't go straight to the chef for placing the order, right? The waiter does that for you. That's what API is. **It's an interface that communicates between applications.**
Here,
-    You/Customer: Client
-    Waiter: API
-    Chef: Server
Hence, in order to get the data from the web servers, we need APIs.

In our example, we are using [FunTranslationAPI](https://funtranslations.com/shakespeare) to fetch the data in JSON format(key - value pair).

Let's call the API then!

## Fetch API

The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers to given URL.

Basic syntax involved:
```js
fetch(url)
    .then(response => {
        // handle the response
    })
    .then(data => console.log(data))
    .catch(error => {
        // handle the error
    });
```

Here in the `fetch()` function we pass the URL of the resource from where we are requesting the data. This will pass the data as a `response` object. The `response` object is the API wrapper for the fetched resource with a number of useful properties and methods to inspect the response. This will then passed to the `data` variable (you can give any name to this) for printing output.

Now, it's time to define the functions.

## Defining Functions() _for some action_

To get our code into some action, we need to define some functions.
```js
function translateFunction(event){
    let inputValue = inputElement.value;   //fetching input value 
    fetch(url)                             //Fetch API call
        .then(response => response.json())
        .then(data => {
            outputElement.innerText = data;
        })
        .catch(() => alert("Shakespeare(Server) is busy! Try after sometime"))
```
Now, let's break it down:
1. We'll extract `inputElement` value into `inputValue` variable. 
2. Making `fetch` API call using the given `url` and then extracting `response` object. This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the `json()` method via using an [arrow](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) function.
3. Setting `data` variable's value to the `outputElement` variable.
4. Finally, error handling with `catch()` function.

Let's try our application. Go to the browser, input your text & click on the translate button. You'll get the following output. 
###### In console
```json
{
    "error": {
        "code": 400,
        "message": "Bad Request: text is missing."
    }
}
```
That's not the output that we were expecting. That's because we've to pass the text to our URL. For that we'll define another function `translatedURL()`.
```js
function translatedURL(inputValue){
    return `${url} ?text= ${inputValue}`;   
}
```
Let's try our app with sample text _Hi. How are you?_ and calling in fetch() function as `fetch(translatedURL(inputValue))` instead of previous `fetch(url)` to concatenate the text message to our server API's URL. We'll get output like this:
```json
{
    "success": {
        "total": 1
    },
    "contents": {
        "translated": "Good morrow. How art thee?", 
        "text": "Hi. How are you?",     
        "translation": "shakespeare"         
    }
}
```
Success! Not so much. Notice that the output text doesn't look pretty. This output is JSON data and we need to extract the translated value from it.

Here,

-    translated: translated text
-    text: input text
-    translation: language of translation being used from FunTranslation API
We refer it by `json.contents.translated`. Now our code should look something like this: 

```js
function translatedURL(inputValue){
    return `${url}?text=${inputValue}`;  
}

function translateFunction(event){
    let inputValue = inputElement.value;    
    let finalURL = translatedURL(inputValue);
    fetch(finalURL)
        .then(response => response.json())
        .then(json => {
            outputElement.innerText = json.contents.translated;
        })
        .catch(() => alert("Shakespeare(Server) is busy! Try after sometime"))
}
```
and we get the following output:
![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/us63l9tbhxnt004el08i.PNG)

**Voila!** We've built our very own Shakespeare Translation Web App with JavaScript Fetch API.

>Note: Funtranslation APIs are free to use, hence they have a limitation of 5 calls/hour. Once it exceeds this limit, it would result in a failure with an error we've mentioned in the `catch()` block.

##Finished for now...

Congrats on making it this far! We've got the basic understanding of DOM scripting i.e. JS in the browser, calling servers, and getting data from there, taking user input and showing user output, and many more things.

Now all that's left for you is to design your own styling with CSS. You can also check out funtranslation [site](https://funtranslations.com) for a similar app with different translation languages.

>[Click here](https://iamshakespeare.netlify.app/) to check out the live project.

Give it a try, create your version of the same and share your experience and feedback on the comments section.

*_Thanks for reading!_*