HTTP Requests in Scala
In this lesson, you will learn how to work with HTTP requests in Scala. HTTP communication is essential for building real-world applications such as REST APIs, microservices, and data-driven systems.
Scala provides powerful libraries to send and receive HTTP requests in a safe, asynchronous, and scalable manner.
What Is an HTTP Request?
An HTTP request is a message sent from a client to a server to request data or perform an action.
- Fetching data from APIs
- Sending data to servers
- Interacting with web services
Most modern applications rely heavily on HTTP communication.
Common HTTP Methods
HTTP defines several request methods, each with a specific purpose.
- GET – Retrieve data
- POST – Send new data
- PUT – Update existing data
- DELETE – Remove data
Choosing an HTTP Library in Scala
Scala does not include a built-in HTTP client, but popular libraries are available.
- Akka HTTP
- STTP
- Play WS
In this lesson, we will use Akka HTTP because it integrates well with concurrency and streams.
Adding Akka HTTP Dependency
Add the following dependency to your build.sbt file.
libraryDependencies += "com.typesafe.akka" %% "akka-http" % "10.2.10"
Creating an Actor System
Akka HTTP requires an Actor System to manage concurrency.
import akka.actor.ActorSystem
implicit val system = ActorSystem("HttpSystem")
Sending a Simple GET Request
The following example sends an HTTP GET request to a public API.
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
val responseFuture =
Http().singleRequest(HttpRequest(uri = "https://api.github.com"))
The request is executed asynchronously and returns a Future.
Handling the HTTP Response
Once the response is received, you can process the status and body.
responseFuture.foreach { response =>
println(response.status)
}
This prints the HTTP status code returned by the server.
Reading the Response Body
The response body is delivered as a stream of bytes.
import akka.util.ByteString
responseFuture.foreach { response =>
response.entity.dataBytes
.runFold(ByteString(""))(_ ++ _)
.foreach(body => println(body.utf8String))
}
This converts the response body into a readable string.
Sending a POST Request
POST requests are used to send data to a server.
val jsonData =
"""{"name": "Scala", "type": "Language"}"""
val request = HttpRequest(
method = HttpMethods.POST,
uri = "https://httpbin.org/post",
entity = HttpEntity(ContentTypes.`application/json`, jsonData)
)
Http().singleRequest(request)
Handling HTTP Errors
Always check the response status to handle errors properly.
responseFuture.foreach { response =>
if (response.status.isSuccess()) {
println("Request successful")
} else {
println(s"Request failed: ${response.status}")
}
}
Timeouts and Reliability
In production systems, network calls can fail or time out.
- Always handle failures
- Use retries when appropriate
- Set request timeouts
This ensures your application remains stable.
Real-World Use Cases
- Calling external REST APIs
- Microservice communication
- Fetching JSON data
- Sending analytics or logs
📝 Practice Exercises
Exercise 1
Send a GET request to any public API and print the response status.
Exercise 2
Create a POST request with JSON data.
Exercise 3
Handle failed HTTP responses gracefully.
✅ Practice Answers
Answer 1
Http().singleRequest(HttpRequest(uri = "https://httpbin.org/get"))
.foreach(r => println(r.status))
Answer 2
val data = """{"id":1}"""
Http().singleRequest(
HttpRequest(
method = HttpMethods.POST,
uri = "https://httpbin.org/post",
entity = HttpEntity(ContentTypes.`application/json`, data)
)
)
Answer 3
responseFuture.foreach { r =>
if (!r.status.isSuccess())
println("Error occurred")
}
What’s Next?
In the next lesson, you will learn about JSON Handling and how Scala applications work with structured data formats.