How To Interact With APIs from a Web App
We are going to build a URL shortening web app using the fetch function to interact with an external service
Imagine you are building a web app that needs to save and query business data from the server-side. Or maybe it must process users’ payments through a third-party provider. In these and many other cases, web apps benefit from a way to request computation from external software. The Fetch API is an answer to that challenge.
The Fetch API has broad support among browsers and is also present in Deno and Node.js server runtimes.
We will cover an introductory use case in this post by building a web app that shorts URLs. While using the app, the user types a long URL and clicks a button. The app requests the SHRTCODE service to respond with a shortened version for that long URL. Then we present this new version to the user.
This project is beginner’s friendly. It aims at those starting web development or unfamiliar with the Fetch API.
Environment
A machine with Node.js and a code editor like Visual Studio Code installed is the only requirement to code along.
The first step is to create a project folder to hold the source code. Inside the new folder, run the following command to initialize an npm package.
npm init -y
We need a webserver to run our app. If you want to use Vite as I did, now is an excellent time to install it.
npm i -D vite
To ensure the plumbing is all set, create an index.html
file with the following markup. Then run Vite with the npx vite
command.
Finally, check if the app is online at the address provided by Vite in the terminal.
Let’s code 🤓.
Input UI
The user needs an input
element to type the URL they want to be shortened and a button
to call the action. See the updated HTML code for that below. In there, we also anticipate a javascript import needed next.
Unfortunately, nothing will happen if someone clicks the button now. Please create a main.js
file beside index.html
so we can change that.
We start by attaching a function to the button click event. Inside the function, we store the long URL typed in the input
and (just for now) print it on the browser console. Take a look.
Fetch
The fetch function makes a dynamic request to another program through the network. Its minimum requirement is the external program URL but is flexible for configuration by various options. When the request completes, the function resolves to a Response object with valuable data about the operation.
The SHRTCODE docs state that to shorten a link like www.google.com
,
we should append it to a base URL like this: https://api.shrtco.de/v2/shorten?url=www.google.com
. The SHRTCODE server then responds with the shortened link if the process is successful.
Let’s try calling fetch
on those terms and logging the response to the console.
You may have noticed that the response signals a successful request, but we can’t find over there the short URL we were expecting. You see, services can respond with various data types to requests. The response object stores this information in an unopinionated bucket of bytes inside its body property.
Since SHRTCODE ship answers in the familiar JSON format, we can use the handy json method to parse the response body into a corresponding javascript object. We do that below and discover that the short URL is available in multiple forms inside the result
property of the parsed object.
Now that we have the short URL, we need a better UI than the browser console to show it to our users.
Hi, a small break to say that you can subscribe for free and never miss new posts from the blog.
Short Link UI
We’ll add an anchor tag to index.html
to show the short URL as a clickable link to the user. We need to update its text and reference values after every API response parse. See below.
We could declare things good as done by now, but there are some minimal improvements I would like to cover with you.
The page will update itself to the short link address If the user clicks it right now. Users tend to expect this kind of link to open in a new tab. We solved that by the setting the anchor target
property to _blank
.
The layout would be more friendly to small screens if we stack the elements vertically. We achieve this by grouping our tags inside a grid
container set to center its children elements on both axes.
The last changes are handled below in the index.html
file.
Conclusion
Playing with third-party APIs is an excellent way to learn how to build feature-rich web apps faster since the backend is already cooked. You can find loads of them by searching for “public API” in your favorite search engine.
I came across the API we used here in this article. Maybe you can use other APIs listed there for your fun projects, but be careful when integrating with APIs requiring access keys. Any user can capture the keys when you leave them in the web app source code.
Finally, the project source code is completely available in this Github repository.
Have a nice one.
If you think this post can help someone, please share it with them. Better yet, subscribe for free and receive fresh content in your inbox every time it is published on the blog. I will never send more than one email a week.