Integrating API Requests for Dynamic Tutor Interaction

Welcome back! In the previous lesson, you set up a basic interface for your personal tutor using Java (Spring Boot) and HTML. This laid the foundation for creating a user-friendly educational web application. Now, we will take the next step by connecting this interface to our backend API. This connection is crucial for transforming our static interface into a dynamic, interactive tutoring experience. By the end of this lesson, you will understand how to integrate the frontend with the backend, enabling real-time communication between the student and the tutor system.

Understanding Fetch API

In this lesson, we will enhance our tutor interface by connecting it to the backend API using the Fetch API. This tool will allow us to capture student input and send it to the server, transforming our tutor into a dynamic application.

The Fetch API is a modern interface that allows you to make network requests from your web page. It provides a more powerful and flexible feature set for handling HTTP requests and responses. With Fetch, you can send and receive data from the server in the background, creating a smoother and more interactive educational experience.

Here's how it works:

  1. Making a Request: When you want to get or send data, you use the fetch() function. You tell it where to send the request (the URL) and what kind of request it is.

  2. Handling the Response: After the request is sent, the server will reply. The Fetch API lets you handle this reply using .then(). You can think of .then() as a way to define what happens after the server responds, similar to how you check your messages after someone replies. It is part of a Promise chain, which means it allows you to specify a sequence of actions that should occur once the asynchronous operation (like a network request) completes successfully, rather than just acting as a simple callback.

  3. Dealing with Errors: Sometimes things go wrong, like if the server is down. The Fetch API lets you handle these problems using .catch(), so your web page can show a message or try again.

Here's a simple example of how the Fetch API works within a function:

In this example, the fetchData function uses the method to send a request to the server. You specify the endpoint and HTTP method and use the and methods to handle the server's response and any errors. This process happens in the background, so your web page stays responsive and interactive.

Initializing Tutor Variables

Now that we have a basic understanding of how HTTP requests work in Spring Boot, let's prepare our tutor application by initializing some variables to store the current session and student IDs. These variables will help us manage and track each tutoring session as we implement dynamic functionalities.

In your HTML file, you can use JavaScript to store these variables:

These variables are initialized to null and will be used to store the session and student IDs once a new tutoring session is created.

Updating the startNewSession Function

Previously, the startNewSession function simply cleared the chat history. Now, we will update it to initialize a new tutoring session by making a request to the backend. In this update, we will also use the browser's localStorage API to persist the studentId across sessions, ensuring that the same student ID is reused even if the page is refreshed or reopened.

The localStorage API is a feature provided by modern web browsers that allows you to store key-value pairs of data directly in the user's browser. This data persists even after the browser is closed or the page is refreshed, making it useful for saving information like a unique studentId that should remain consistent across multiple sessions.

In your HTML file, you can use JavaScript to send a request to the Spring Boot backend:

This updated function now makes a POST request to the /api/tutor/create endpoint on our Spring Boot backend. When the server responds, we process the JSON data and store the returned sessionId in our previously initialized variable. We then clear the message container to start a fresh conversation and display a welcome message from the assistant. If there's an error during this process, we display an error message in the chat interface to notify the user that there was a problem creating the tutoring session.

Enhancing the sendQuery Function

The sendQuery function will now send the student's question to the server and display the tutor's response in the interface.

In your HTML file, you can use JavaScript to send the query:

This enhanced sendQuery function now handles the complete interaction flow between the student and the tutor. First, it retrieves the student's query from the input field, trims any whitespace, and checks if the query is empty. If there's a valid query, it displays the student's message in the chat interface using the appendMessage function and clears the input field.

Then, it sends the query to the backend by making a POST request to the /api/tutor/ask endpoint. The request includes important headers like 'Content-Type': 'application/json' to tell the server we're sending JSON data. The body parameter uses JSON.stringify() to convert our JavaScript object (containing the student ID, session ID, and question) into a JSON string that can be transmitted to the server. This conversion is essential because HTTP requests can only send text, not JavaScript objects directly.

Sample API Response Bodies

To help you better understand how the backend communicates with the frontend, let's look at some sample response bodies you might receive from the API endpoints.

When a tutoring session is successfully created via the /api/tutor/create endpoint, the Spring Boot backend returns a JSON object containing the session ID:

When a student's question is successfully processed via the /api/tutor/ask endpoint, the backend returns a JSON object containing the tutor's response message:

On the other hand, if something goes wrong — such as a missing or invalid session ID — the backend will return an error response with an appropriate HTTP status code (like 400 for bad requests or 500 for server errors). The specific error format will depend on your Spring Boot error handling configuration, but typically includes details about what went wrong.

In your frontend, you can check the response status using resp.ok and show a helpful message to the user when errors occur, ensuring a smooth and user-friendly experience.

Summary and Next Steps

In this lesson, you learned how to connect the tutor interface to a backend API using Java (Spring Boot) and HTTP requests. We covered the setup of API endpoints, the integration of the frontend with the backend, and the implementation of tutoring functionality. This connection is a crucial step in creating a dynamic and interactive educational application.

As you move on to the practice exercises, focus on reinforcing these concepts and experimenting with the code. This hands-on practice will deepen your understanding and prepare you for the next unit, where we will continue to enhance the personal tutor's capabilities. Keep up the great work, and let's continue building this exciting educational tool together!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal