Making GET Requests and Handling Responses

Making GET Requests and Handling Responses

Welcome to the second lesson in our journey of interacting with APIs using Scala 3 and the Requests-Scala library. In the previous lesson, we laid a strong foundation for understanding RESTful APIs and how HTTP requests facilitate interactions with them. We used curl to manually send a GET request to an endpoint. Now, we are transitioning to automating this process using Scala. This lesson introduces Requests-Scala, which allows us to send HTTP requests effortlessly in our Scala applications, making it an invaluable tool in the realm of web development and API integration.

Setting Up the Environment

To make HTTP requests in Scala, we use the Requests-Scala library, which provides a simple and powerful API for handling HTTP requests. To get started, you'll need to add the following dependencies to your build.sbt file:

libraryDependencies += "com.lihaoyi" %% "requests" % "0.6.9"
libraryDependencies += "com.lihaoyi" %% "ujson" % "3.1.3"

Once the dependencies are added, you can import the necessary packages in your Scala code, making their functionalities available for sending HTTP requests and handling JSON:

import requests.*
import ujson.*

With this setup, you'll be equipped to automate requests, saving time and boosting efficiency in your development workflow.

Defining the Base URL

When interacting with an API, it's helpful to define a base URL for the service you're communicating with. This makes your code more modular and easy to maintain, allowing you to change the root of your API URL in one place without modifying each request.

// Base URL for the API
val baseUrl = "http://localhost:8000"

By setting this baseUrl, we can easily concatenate endpoints for different services within the API, making our code cleaner and more adaptable.

Performing a Basic GET Request

Let's dive into the process of fetching data from an API using Scala's Requests-Scala library. Our goal is to retrieve a list of to-do items from the /todos endpoint using the GET method.

// Fetch all todos using the get method
val responseTry = Try(requests.get(s"$baseUrl/todos"))

// Handle response success or failure
responseTry match {
  case Success(response) =>
    // Print raw response
    println("Raw Response:")
    println(response.text())

    // Continue with response handling based on status codes ...
  case Failure(exception) =>
    println(s"Failed to fetch todos: ${exception.getMessage}")
}

By using the requests.get() method, we send a GET request to the constructed full URL. The response from the server, stored in the variable response, is then printed using response.text(), which gives us the raw response body as a string.

Here's an example of what the raw response might look like:

Raw Response:
[
  {
    "description": "Milk, eggs, bread, and coffee",
    "done": false,
    "id": 1,
    "title": "Buy groceries"
  },
  {
    "description": "Check in and catch up",
    "done": true,
    "id": 2,
    "title": "Call mom"
  },
  {
    "description": "Summarize Q4 performance metrics",
    "done": false,
    "id": 3,
    "title": "Finish project report"
  },
  {
    "description": "30 minutes of cardio",
    "done": true,
    "id": 4,
    "title": "Workout"
  }
]

This raw output allows us to see the immediate result returned by the server, serving as a starting point for further processing of the data.

Handling Successful Requests (Status Code: 200)

Handling Bad Requests (Status Code: 400)

Errors can happen on either the client or server side, so it's important to handle them properly. A 400 status code means there was a mistake in the request, often due to incorrect syntax from the client side. To understand these errors better, you can print the response body as JSON, which provides more details about what went wrong and can help you fix the issue.

case Success(response) if response.statusCode == 400 =>
  println("\nBad Request. The server could not understand the request due to invalid syntax.")
  val error = ujson.read(response.text())
  println(s"Error Details: $error")

Handling Unauthorized Requests (Status Code: 401)

A 401 status code indicates an unauthorized request, often due to missing or invalid credentials. This situation requires the user to address authentication problems to proceed.

case Success(response) if response.statusCode == 401 =>
  println("\nUnauthorized. Access is denied due to invalid credentials.")
  val error = ujson.read(response.text())
  println(s"Error Details: $error")

Handling Not Found Errors (Status Code: 404)

When encountering a 404 status code, it means the requested resource is not found, often pointing to a missing resource or an incorrect endpoint.

case Success(response) if response.statusCode == 404 =>
  println("\nNot Found. The requested resource could not be found on the server.")
  val error = ujson.read(response.text())
  println(s"Error Details: $error")

Handling Internal Server Errors (Status Code: 500)

A 500 status code reflects an internal server error, indicating the server encountered an unexpected situation. Such cases usually require investigation on the server side to resolve the issue.

case Success(response) if response.statusCode == 500 =>
  println("\nInternal Server Error. The server has encountered a situation it doesn't know how to handle.")
  val error = ujson.read(response.text())
  println(s"Error Details: $error")

Handling Unexpected Status Codes

For responses falling outside the common codes, a generic approach captures these cases, ensuring all responses are analyzed for potential issues.

case Success(response) =>
  println(s"\nUnexpected Status Code: ${response.statusCode}")
  val error = ujson.read(response.text())
  println(s"Error Details: $error")

By handling these diverse status codes, we ensure robust API interactions and better understand the server's communication.

Conclusion, Key Takeaways, and Next Steps

In this lesson, we've explored the powerful capability of Scala's Requests-Scala library to make GET requests to an API. We've seen how to retrieve and handle responses effectively, interpreting HTTP status codes to understand the server's communication. This knowledge is crucial for creating reliable interactions with APIs. As you move on to the practice exercises, focus on experimenting with the code snippets and handling various status codes to solidify your understanding. In future lessons, we will build on this foundation, unlocking the potential to perform more complex tasks like updating and manipulating API data. Keep up the great work as you advance through the course!

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