Build an AI Text Shortener App with Rapid's API Hub and Next.js

Fri Apr 14 2023

15 min read

In this blog post, you will learn about building a full-stack project using React, Next.js, and Rapid's API Hub. Whether you're a seasoned developer or just starting, this tutorial will cover advanced React and Next.js concepts to help you create dynamic web pages and build powerful backends.

As a web developer, you're likely familiar with React, the popular JavaScript library for building user interfaces. Next.js is a powerful framework that builds on React, providing features like server-side rendering and static site generation. And Rapid's API Hub is a massive collection of APIs that allows you to easily connect to and consume APIs, providing access to a wide range of data sources.

These technologies create a powerful toolkit for building dynamic and interactive web applications easily. In this tutorial, you'll learn how to use them to build a full-stack web application from start to finish.

Whether you're a seasoned developer looking to expand your skill set or a beginner just getting started, this tutorial has something for everyone. We'll cover advanced concepts like server-side rendering, data fetching, state management, and Next.js's API Routes while providing clear and concise explanations for those new to these technologies.

Loading component...

By the end of this tutorial, you'll have a solid understanding of how to use React, Next.js, and Rapid's API Hub to create a complete web application with a responsive user interface and a powerful backend. So, let's dive in and get started on our full-stack journey!

What is an API?

API stands for Application Programming Interface, and it's essentially a way for different applications to communicate. APIs allow us to send and receive data between different systems, which is useful when building web applications.

APIs act as a bridge between different software systems, enabling them to interact and communicate. They provide a set of rules, protocols, and tools for developers to access the functionality and data of an application or service without needing to understand the underlying code or architecture.

In web development, APIs are essential for enabling data exchange between the front-end and back-end of an application. In real-time, web applications can retrieve and display information from external sources, such as social media platforms, payment gateways, or databases.

APIs can take many different forms, but they all have one thing in common: they expose a specific set of functionalities or data that can be accessed through a defined set of endpoints or methods. These endpoints can be queried using HTTP request methods, such as GET, POST, PUT, and DELETE, and they return structured data in a format like JSON or XML.

APIs provide developers with a standardized and scalable way to integrate different services and data sources into their applications, saving time and effort in the development process. With APIs, developers can focus on building their applications' user interface and business logic without worrying about the underlying technical details of how the data is retrieved and managed.

When it comes to APIs, two popular types are REST and GraphQL.

REST APIs

REST stands for Representational State Transfer and is a widely used architectural style for building web APIs. REST APIs are based on HTTP and use standard CRUD (Create, Read, Update, Delete) operations to interact with data resources. They typically return data in JSON or XML format and use URLs and HTTP methods to define endpoints and actions.

GraphQL APIs

GraphQL, on the other hand, is a query language and runtime for building APIs. Unlike REST, which follows a strict schema, GraphQL allows clients to request only the data they need and returns a JSON response that matches the structure of the query. This makes it more efficient and flexible than REST, particularly for complex data structures.

While REST is a well-established and widely adopted standard, GraphQL has gained popularity recently for its ability to simplify data fetching and reduce over-fetching and under-fetching of data. However, it's worth noting that each approach has its strengths and weaknesses, and the choice between REST and GraphQL will depend on the specific requirements of your project.

What is Rapid's API Hub?

Rapid's API Hub is a collection of APIs that you can use to add functionality to your applications. It includes APIs for text analysis, image recognition, and weather data. The best part is that these APIs are incredibly easy to use - you don't need to worry about complex authentication or API keys. Rapid's API Hub takes care of all of that for you.

Loading component...

Choosing the right API for your project is important. You want to ensure that the API you choose provides the functionality you need and is easy to use.

You will use the TLDRThis API from Rapid’s API Hub for this project. This API allows you to take large blocks of text and shorten them down to a specified length, which is perfect for things like social media posts or article previews.

Loading component...

Setting up the development environment

Before you build your full-stack project with React, Next.js, and Rapid's API Hub, you must set up your development environment. This involves ensuring you have all the necessary tools and dependencies installed on your machine.

The first step is to ensure that Node.js and npm (Node Package Manager) are installed on your computer. Node.js is a JavaScript runtime that allows you to run JavaScript code outside of a web browser, while npm is a package manager that allows you to install and manage dependencies easily.

To check if Node.js and npm are installed on your machine, open your terminal or command prompt and type the following commands:

bash
node -v
npm -v

These commands will print out the versions of Node.js and npm, respectively. If you see a version number printed out for both commands, that means Node.js and npm are already installed on your machine. If not, you'll need to download and install them before proceeding.

You can download the latest Node.js and npm from the official Node.js website. Follow the installation instructions for your operating system, and choose the LTS (Long-Term Support) version of Node.js, as this will provide the most stable and reliable platform for your project.

Once you have Node.js and npm installed, you can move on to setting up your development environment for your full-stack project. This will involve installing additional dependencies, such as Next.js and Tailwind CSS, which we'll cover in the next sections of this tutorial.

Loading component...

Creating a new Next.js application

Now that you have set up your development environment, you can create a new Next.js application. Next.js is a popular framework for building React applications, and it offers many features and optimizations that make it an ideal choice for building full-stack projects.

To create a new Next.js application, you can use the npx create-next-app command. This command will generate a new Next.js project with all the necessary files and dependencies.

In your terminal or command prompt, navigate to the directory where you want to create your new Next.js application. Once you're in the desired directory, type the following command:

bash
npx create-next-app

The CLI will ask you for a few prompts. The app will use TypeScript, ESLint, and Tailwind CSS for this project. So, you can go ahead and select yes only for them. You can select the default configuration for the import aliases.

This command will create a new Next.js application named "ai-text-shortener-app". The npx command executes the create-next-app command without having to install it globally on your machine.

After the command finishes running, you should see a message indicating that your new Next.js application has been created successfully. You can now navigate into the newly created directory by typing:

bash
cd ai-text-shortener-app

This will take you to the root directory of your new Next.js application, where you'll find all the necessary files and folders to start your project.

To start the development server for your newly created Next.js application, simply navigate to your project directory in your terminal or command prompt and type the following command:

bash
npm run dev

This command will start the server and allow you to build your app. It's important to keep this server running while you work on your project, as it will automatically update your app whenever you make changes to your code.

Once the server runs, you can preview your app by visiting localhost:3000 in your web browser. This will display a preview of your application.

Now that your development environment is set up and your server is running, you can start building your full-stack project.

Installing Tailwind CSS

Tailwind CSS is a popular utility-first CSS framework that can quickly and easily style your Next.js application. This section will cover installing and integrating Tailwind CSS into your Next.js project.

Step 1: Install Tailwind CSS

To install Tailwind CSS, navigate to your project directory in your terminal or command prompt and type the following command:

bash
npm install -D tailwindcss postcss autoprefixer

This command will install the latest version of Tailwind CSS and add it to your project's dependencies.

Step 2: Create a Tailwind CSS configuration file

Next, you'll need to create a configuration file for Tailwind CSS. To do this, type the following command in your terminal or command prompt:

npx tailwindcss init -p

This command will create a new configuration file for Tailwind CSS in your project directory. You can customize this file to suit your needs and preferences.

Step 3: Integrate Tailwind CSS with Next.js

Modify your tailwind.config.js file with the following:

js
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
// Or if using the `src` directory:
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

Step 4: Import Tailwind CSS styles into your project

Add the @tailwind directives to your globals.css file.

css
@tailwind base;
@tailwind components;
@tailwind utilities;

Step 5: Restart the Next.js development server

If the development server of your project is already running, stop it and restart the server using the following command:

bash
npm run dev

Your app will start running on localhost:3000, and if you add Tailwind CSS’s utility classes to your app, you should be able to see them working as expected.

Implement the heading and description of the app

To implement the heading and the description of the app, you can remove the code present in pages/index.tsx and replace it with the following code:

tsx
export default function Home() {
return (
<div className="mx-auto w-full max-w-lg py-24 space-y-24 min-h-screen flex flex-col justify-center">
<div className="space-y-6 w-full text-center">
<h1 className="text-6xl font-bold">Shorten AI</h1>
<p>Unlock the power of text summarization with AI.</p>
</div>
</div>
);
}

In the above code, Shorten AI is the heading, and Unlock the power of text summarization with AI. is the app's description.

Now, if we visit localhost:3000 on our browser, we should be able to view the following:

Implementing the logic for the textarea and the button components

You can store the value that the user will enter in the textarea inside the text React state. You can use the summary state to store the value of the summary that the API will return. Also, you can use one state called loading to store the app's current state. Using the loading state, you can show loaders or disable the button and the textarea.

Let's implement the above in the pages/index.tsx file. Add the following code to the pages/index.tsx file:

tsx
import { useState } from "react";
export default function Home() {
// 1. Storing the text that the user will enter in the textarea -> String
const [text, setText] = useState("");
// 2. Saving the summary that the AI API will send us -> String
const [summary, setSummary] = useState("");
// 3. For storing the current state of the app -> Boolean
const [loading, setLoading] = useState(false);
return (
// Rest of the return function
);
}

Then, you must write the logic for the textarea and the button. Add the following code to the same pages/index.tsx file:

tsx
// All the import statements
const Home = () => {
// All the React state definitions should come here
const handleClick = async () => {
// This function will be defined shortly
};
return (
<div className="mx-auto w-full max-w-lg py-24 space-y-24 min-h-screen flex flex-col justify-center">
<div className="space-y-6 w-full text-center">
<h1 className="text-6xl font-bold">Shorten AI</h1>
<p>Unlock the power of text summarization with AI.</p>
</div>
<div className="space-y-4 w-full">
<div className="p-4 border rounded flex flex-col space-y-4 bg-gray-50">
<textarea
className="border rounded p-4"
value={text}
onChange={(e) => setText(e.target.value)}
disabled={loading}
/>
<button
onClick={handleClick}
className="bg-black text-white rounded px-4 py-2"
>
Summarize
</button>
</div>
</div>
</div>
);
};
export default Home;

As you can see above, the textarea is a controlled React component. The prop text is getting updated as a user types inside the textarea.

If you visit localhost:3000, you should be able to view the following:

When a user clicks on the button component, the handleClick function is called. The handleClick function calls the serverless function to get the value from the AI API from Rapid's API Hub.

Replace the code for the handleClick function with the following code:

tsx
const handleClick = async () => {
setLoading(true);
try {
const response = await fetch("/api/summarize", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
text: text,
min_length: 100,
max_length: 300,
}),
});
const data = await response.json();
setSummary(data.summary);
} catch (error) {
console.log(error);
} finally {
setLoading(false);
}
};

The handleClick function above calls the /api/summarize API endpoint. That is the endpoint for the serverless function, which will be defined next.

The body of the API request contains all the necessary information that the AI API requires.

You can display the summary that the AI API will return by adding the following code inside the return:

tsx
// All the import statements
export default function Home() {
// Rest of the function
return (
<div className="mx-auto w-full max-w-lg py-24 space-y-24 min-h-screen flex flex-col justify-center">
// Rest of the return function
<div className="border space-y-2 rounded bg-white overflow-hidden">
<div className="p-2">{summary}</div>
</div>
</div>
);
}

Now, if you visit [localhost:3000](localhost:3000, you should view the following:

Implementing the API Route for fetching the data

To implement the API Route for fetching the data from the AI API, you can create a new file inside the pages/api directory and call it summarize.ts. The pages/api/summarize.ts file will contain the following code:

ts
import { NextApiRequest, NextApiResponse } from "next";
type Data = {
summary: string;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-RapidAPI-Key": process.env.RAPID_API_KEY
? process.env.RAPID_API_KEY
: "",
"X-RapidAPI-Host": process.env.RAPID_API_HOST
? process.env.RAPID_API_HOST
: "",
},
body: JSON.stringify(req.body),
};
if (req.method === "POST") {
try {
const response = await fetch(
"https://tldrthis.p.rapidapi.com/v1/model/abstractive/summarize-text/",
options
);
const json = await response.json();
res.status(200).json({
summary: json.summary,
});
} catch (error) {
res.status(500);
}
} else {
res.status(500);
}
}

In the above code, the handler function will first check if the method of the request is POST or not. If the request is anything other than POST, the function will return a status of 500. This will indicate that there is an error with the request.

If the request method is POST, then the handler function will request the AI API from Rapid's API Hub, and the response will be sent to the client. Using the try/catch block, the handler function also checks if there is an error with the request to the AI API. If the request is unsuccessful, the status code of 500 will be sent to the client.

Also, you need to define the two environment variables RAPID_API_KEY and RAPID_API_HOST. To do that, you need to create a new file called .env.local in the root of your project with the following:

bash
RAPID_API_KEY=<your-rapid-api-key>
RAPID_API_HOST=tldrthis.p.rapidapi.com

Once you add the file, you can restart the Next.js development server. If you now visit localhost:3000, you should be able to view that the correct summary is being returned by the AI API from Rapid's API Hub.

Conclusion

You should now understand how to create a full-stack web application that integrates with external APIs, handles user input, and displays data dynamically. This guide covered a wide range of topics, from setting up your development environment, creating a frontend with React and Next.js, building a backend, and integrating with Rapid's API Hub.