Build your own Shakespeare Translation Web App with JavaScript Fetch API

nayyyhaa

Neha Gupta

Posted on April 10, 2021

Build your own Shakespeare Translation Web App with JavaScript Fetch API

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

Try out the app here

Source Code

In case you get lost while following along, you can grab the source code from here.

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
<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>
Enter fullscreen mode Exit fullscreen mode

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
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
Enter fullscreen mode Exit fullscreen mode

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.

translateBtnElement.addEventListener("click", translateFunction);
Enter fullscreen mode Exit fullscreen mode

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 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:

fetch(url)
    .then(response => {
        // handle the response
    })
    .then(data => console.log(data))
    .catch(error => {
        // handle the error
    });
Enter fullscreen mode Exit fullscreen mode

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.

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"))
Enter fullscreen mode Exit fullscreen mode

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 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
{
    "error": {
        "code": 400,
        "message": "Bad Request: text is missing."
    }
}
Enter fullscreen mode Exit fullscreen mode

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().

function translatedURL(inputValue){
    return `${url} ?text= ${inputValue}`;   
}
Enter fullscreen mode Exit fullscreen mode

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:

{
    "success": {
        "total": 1
    },
    "contents": {
        "translated": "Good morrow. How art thee?", 
        "text": "Hi. How are you?",     
        "translation": "shakespeare"         
    }
}
Enter fullscreen mode Exit fullscreen mode

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:
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"))
}
Enter fullscreen mode Exit fullscreen mode

and we get the following output:
output

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 for a similar app with different translation languages.

Click here 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!

💖 💪 🙅 🚩
nayyyhaa
Neha Gupta

Posted on April 10, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related