### Simple GET Request Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/requester.md Demonstrates a basic GET request to a specified URL and prints the status code and response text. ```scala // Simple GET request val response = requests.get("https://api.github.com/users/lihaoyi") println(response.statusCode) // 200 println(response.text()) // JSON response body ``` -------------------------------- ### Installation Examples for requests-scala Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Shows how to add the requests-scala library to your project using different build tools like Mill, SBT, Gradle, and Scala CLI. ```scala // Mill ivy"com.lihaoyi::requests:0.9.2" ``` ```scala // SBT "com.lihaoyi" %% "requests" % "0.9.2" ``` ```scala // Gradle compile "com.lihaoyi:requests_2.12:0.9.2" ``` ```scala // Scala CLI //> using dep "com.lihaoyi::requests:0.9.2" ``` -------------------------------- ### Authentication Examples Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Provides examples for different authentication methods, including basic authentication, bearer tokens, and proxy authentication. ```scala // Basic authentication val response = requests.get( "https://api.github.com/user", auth = ("username", "password") ) ``` ```scala // Bearer token val response = requests.get( "https://api.github.com/user", auth = RequestAuth.Bearer("ghp_abc123...") ) ``` ```scala // Proxy authentication val response = requests.get( "https://api.example.com", proxy = ("proxy.corp.com", 8080), auth = RequestAuth.Proxy("proxyuser", "proxypass") ) ``` -------------------------------- ### Dispatch Basic GET Request Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md A concise example of making a GET request using the Dispatch library. It directly maps the response to a String. ```scala import dispatch._, Defaults._ val svc = url("http://api.hostip.info/country.php") val country = Http.default(svc OK as.String) ``` -------------------------------- ### Generated Proxy Authentication Header Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/authentication-ssl.md An example of the `Proxy-Authorization: Basic` header generated for proxy authentication. ```text Proxy-Authorization: Basic cHJveHl1c2VyOnByb3h5cGFzcw== ``` -------------------------------- ### Generated Basic Authentication Header Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/authentication-ssl.md An example of the `Authorization: Basic` header generated for HTTP Basic Authentication. ```text Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= ``` -------------------------------- ### sttp Basic GET Request with Parameters Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Demonstrates a GET request using sttp, specifying response as string and adding query parameters. It uses HttpURLConnectionBackend for execution. ```scala import sttp.client3._ val request = basicRequest.response(asStringAlways) .get(uri"https://api.github.com/search" .addParams(Map("q" -> "http language:scala", "sort" -> "stars"))) val backend = HttpURLConnectionBackend() val response = backend.send(request) println(response.body) ``` -------------------------------- ### Making a GET Request Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Demonstrates how to perform a basic HTTP GET request and access various parts of the response, such as status code, text, bytes, content type, headers, and cookies. ```scala import requests._ val response = requests.get("https://api.github.com/users/lihaoyi") println(response.statusCode) // 200 println(response.text()) // Response body as string println(response.bytes) // Response body as bytes println(response.contentType) // Some("application/json; charset=utf-8") println(response.headers) // All response headers println(response.cookies) // Response cookies ``` -------------------------------- ### Making Other HTTP Requests (PUT, DELETE, HEAD, OPTIONS, PATCH) Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Shows examples of making HTTP requests using methods other than GET and POST, including PUT, DELETE, HEAD, OPTIONS, and PATCH, with optional data payloads. ```scala val response = requests.put("https://api.example.com/users/123", data = Map("name" -> "bob")) val response = requests.delete("https://api.example.com/users/123") val response = requests.head("https://api.example.com/data") val response = requests.options("https://api.example.com/data") val response = requests.patch("https://api.example.com/users/123", data = Map("status" -> "active")) ``` -------------------------------- ### Session HTTP Methods Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/session.md Demonstrates how to create a Session and make GET and POST requests, overriding session defaults for individual requests. ```scala val session = Session( headers = Map("User-Agent" -> "MyApp/1.0"), auth = ("user@example.com", "password") ) // All requests use session headers and auth val users = session.get("https://api.example.com/users") val data = session.post("https://api.example.com/data", data = Map("key" -> "value")) // Can override per-request val publicData = session.get( "https://api.example.com/public", auth = RequestAuth.Empty // Override session auth ) ``` -------------------------------- ### Make a GET Request and Inspect Response Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Demonstrates how to make a GET request to a GitHub API endpoint and access the response's status code, headers, and text content. ```scala val r = requests.get("https://api.github.com/users/lihaoyi") r.statusCode // 200 r.headers("content-type") // Buffer("application/json; charset=utf-8") r.text() // {"login":"lihaoyi","id":934140,"node_id":"MDQ6VXNlcjkzNDE0MA==",... ``` -------------------------------- ### Basic GET Request with Parameters Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Demonstrates a simple GET request to the GitHub API with query parameters using Requests-Scala. The response text can be accessed directly. ```scala val r = requests.get( "https://api.github.com/search/repositories", params = Map("q" -> "http language:scala", "sort" -> "stars") ) r.text() // {"login":"lihaoyi","id":934140,"node_id":"MDQ6VXNlcjkzNDE0MA==",...} ``` -------------------------------- ### Play-WS Basic GET Request Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Illustrates a GET request using Play-WS, which also relies on Akka for system and streaming management. It demonstrates handling the response body and closing the client. ```scala import akka.actor.ActorSystem import akka.stream.ActorMaterializer import play.api.libs.ws._ import play.api.libs.ws.ahc._ import scala.concurrent.Future import DefaultBodyReadables._ import scala.concurrent.ExecutionContext.Implicits._ // Create Akka system for thread and streaming management implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() // Create the standalone WS client // no argument defaults to a AhcWSClientConfig created from // "AhcWSClientConfigFactory.forConfig(ConfigFactory.load, this.getClass.getClassLoader)" val wsClient = StandaloneAhcWSClient() wsClient.url("http://www.google.com").get() .map { case response ⇒ val statusText: String = response.statusText val body = response.body[String] println(s"Got a response $statusText") }. andThen { case _ => wsClient.close() } andThen { case _ => system.terminate() } ``` -------------------------------- ### GET Request with Custom Headers and Authentication Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/requester.md Illustrates making a GET request with custom HTTP headers and basic authentication credentials. ```scala // With custom headers and authentication val resp = requests.get( "https://api.github.com/user", headers = Map("Accept" -> "application/vnd.github.v3+json"), auth = ("username", "password") ) ``` -------------------------------- ### Using Package-Level Functions and Streaming POST Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/requester.md Demonstrates how to use the package-level convenience functions for making GET requests and streaming a POST request with data. This is useful for common request patterns. ```Scala // Using package-level convenience functions val response = requests.get("https://api.github.com/users/lihaoyi") val streamable = requests.post.stream("https://httpbin.org/post", data = "content") ``` -------------------------------- ### Session Configuration and Usage Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/session.md Demonstrates how to create a Session with custom headers, authentication, timeouts, and other configurations. It also shows how to use the session to make GET and POST requests, and the importance of closing the session. ```APIDOC ## Session Configuration Example ```scala val apiSession = Session( headers = Map( "User-Agent" -> "MyApp/1.0", "Accept" -> "application/json" ), auth = RequestAuth.Bearer("eyJ0eXAiOiJKV1QiLCJhbGc..."), readTimeout = 30000, // 30 seconds connectTimeout = 5000, // 5 seconds maxRedirects = 10, persistCookies = true ) try { // All requests use the configured defaults val users = apiSession.get("https://api.example.com/users") val user = apiSession.get("https://api.example.com/users/123") val created = apiSession.post( "https://api.example.com/users", data = Map("name" -> "Alice", "email" -> "alice@example.com") ) } finally { apiSession.close() } ``` ``` -------------------------------- ### Generated Bearer Token Header Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/authentication-ssl.md An example of the `Authorization: Bearer` header generated for Bearer Token Authentication. ```text Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc... ``` -------------------------------- ### Adding Query Parameters to a GET Request Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Demonstrates how to include query parameters in a GET request by providing a Map of key-value pairs. ```scala val response = requests.get( "https://api.github.com/search/repositories", params = Map( "q" -> "http language:scala", "sort" -> "stars" ) ) ``` -------------------------------- ### Cookie Persistence Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/session.md Demonstrates how sessions automatically handle cookie persistence when `persistCookies` is set to true, and how to manually manage cookies if needed. ```APIDOC ## Cookie Persistence Sessions automatically handle cookies when `persistCookies = true`: **Example**: ```scala val session = Session() // First request sets a cookie val r1 = session.get("https://httpbin.org/cookies/set?user=alice") // Second request automatically includes the cookie val r2 = session.get("https://httpbin.org/cookies") println(r2.text()) // {"cookies":{"user":"alice"}} session.close() ``` Manual cookie management is also possible: ```scala val session = Session(persistCookies = false) val r1 = session.get("https://httpbin.org/cookies/set?token=xyz") val cookies = r1.cookies // Extract cookies from response val r2 = session.get( "https://httpbin.org/cookies", cookies = cookies // Pass explicitly ) session.close() ``` ``` -------------------------------- ### Concurrent Request Execution Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/REFERENCE.md Demonstrates how to perform multiple concurrent requests using Scala's Future and Await, managing a session and collecting results. ```scala val session = Session() val futures = (1 to 100).map { i => scala.concurrent.Future { session.get(s"https://api.example.com/item/$i") } } val results = scala.concurrent.Await.result( scala.concurrent.Future.sequence(futures), scala.concurrent.duration.Duration.Inf ) session.close() ``` -------------------------------- ### Configuration Resolution Hierarchy Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/REFERENCE.md Explains the order in which configuration parameters are resolved, starting from per-request settings and falling back to session and package-level defaults. ```text Per-Request Parameter ├─ If provided: use it └─ If not provided: use session default ├─ If Session exists: use it └─ If not provided: use package-level default ``` -------------------------------- ### NIO Path Body Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Shows how to upload a file using java.nio.file.Path, leveraging NIO for file operations. Similar to java.io.File, it sets Content-Type and Content-Length. ```Scala import java.nio.file.Paths val path = Paths.get("data.json") requests.post("https://api.example.com/upload", data = path) ``` -------------------------------- ### Http4s Client Request Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Example of making a request with Http4s, including setting Authorization and Accept headers. The response is expected as a String. ```scala import org.http4s.client.dsl.io._ import org.http4s.headers._ import org.http4s.MediaType val request = GET( Uri.uri("https://my-lovely-api.com/"), Authorization(Credentials.Token(AuthScheme.Bearer, "open sesame")), Accept(MediaType.application.json) ) httpClient.expect[String](request) ``` -------------------------------- ### Using Client Certificates Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Use this snippet to make a GET request with a client certificate from a PKCS 12 archive. Ensure the archive path is correct. ```scala requests.get( "https://client.badssl.com", cert = "./badssl.com-client.p12" ) ``` -------------------------------- ### HTTP Methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH) Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/session.md Sessions expose standard HTTP methods that can be used to make requests. These methods accept the same parameters as the package-level API and override session defaults when specified. ```APIDOC ## HTTP Methods Sessions provide the same HTTP methods as the package-level API. All parameters from `Requester.apply()` are available and override session defaults: ```scala def get(url: String, ...): Response def post(url: String, ...): Response def put(url: String, ...): Response def delete(url: String, ...): Response def head(url: String, ...): Response def options(url: String, ...): Response def patch(url: String, ...): Response // unofficial ``` **Example**: ```scala val session = Session( headers = Map("User-Agent" -> "MyApp/1.0"), auth = ("user@example.com", "password") ) // All requests use session headers and auth val users = session.get("https://api.example.com/users") val data = session.post("https://api.example.com/data", data = Map("key" -> "value")) // Can override per-request val publicData = session.get( "https://api.example.com/public", auth = RequestAuth.Empty // Override session auth ) ``` ``` -------------------------------- ### String Body Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Shows how to send a plain string as the request body, which is implicitly converted to UTF-8 bytes. Also demonstrates sending JSON as a string. ```Scala requests.post( "https://httpbin.org/post", data = "Hello World" ) // JSON as string requests.post( "https://api.example.com/data", data = "{\"user\": \"alice\", \"age\": 30}" ) ``` -------------------------------- ### Streaming GET Request with Configuration Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-config.md Illustrates how to perform a streaming GET request using a configured Request object with a specified read timeout. The `onHeadersReceived` callback can be used for handling headers, and data is processed via `readBytesThrough`. ```scala val req = Request( url = "https://api.example.com/large-file", readTimeout = 30000 ) requests.get.stream( req, data = RequestBlob.EmptyRequestBlob, chunkedUpload = false, onHeadersReceived = null ).readBytesThrough { inputStream => // Process streaming data } ``` -------------------------------- ### Adding Custom Headers to a GET Request Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Shows how to set custom request headers, such as User-Agent and Accept, by providing a Map of header names and values. ```scala val response = requests.get( "https://api.github.com/user", headers = Map( "User-Agent" -> "MyApp/1.0", "Accept" -> "application/vnd.github.v3+json" ) ) ``` -------------------------------- ### Custom SSL Context for Requests Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Make a GET request using a pre-initialized SSLContext for custom SSL configurations. This allows for advanced control over the SSL handshake. ```scala val sslContext: SSLContext = //initialized sslContext requests.get( "https://client.badssl.com", sslContext = sslContext ) ``` -------------------------------- ### Byte Array Body Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Illustrates sending raw binary data using an Array[Byte]. This is useful for non-textual data. It also shows creating bytes from an encoded string. ```Scala val bytes = Array[Byte](1, 2, 3, 4, 5) requests.post("https://api.example.com/binary", data = bytes) // From encoded string val utf8Bytes = "Raw data".getBytes("UTF-8") requests.post("https://api.example.com/raw", data = utf8Bytes) ``` -------------------------------- ### Custom SSL Context with Pinning Trust Manager Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/authentication-ssl.md Implement a custom `X509TrustManager` for certificate pinning or other advanced validation logic. This example demonstrates a basic pinning trust manager. ```scala import javax.net.ssl._ import java.security.cert.X509Certificate // Custom trust manager that accepts only specific certificates class PinningTrustManager extends X509TrustManager { override def getAcceptedIssuers: Array[X509Certificate] = new Array(0) override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {} override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = { // Verify certificate fingerprint or other custom logic val cert = chain(0) val fingerprint = // compute certificate fingerprint if (!expectedFingerprint.equals(fingerprint)) { throw new CertificateException("Certificate fingerprint mismatch") } } } val sslContext = SSLContext.getInstance("TLS") sslContext.init(null, Array[TrustManager](new PinningTrustManager()), null) val response = requests.get( "https://pinned.example.com", sslContext = sslContext ) ``` -------------------------------- ### POST Request with Gzip Compression Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Example of sending a large string request body compressed using Gzip. Ensure the server is configured to handle Gzip compression. ```scala requests.post( "https://api.example.com/upload", data = "Large string data...", compress = requests.Compress.Gzip ) ``` -------------------------------- ### File Body Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Demonstrates uploading a file using java.io.File. The Content-Type is set to application/octet-stream and Content-Length to the file size. The file is read only when the request is sent. ```Scala val file = new java.io.File("data.json") requests.post("https://api.example.com/upload", data = file) // File is read only when the request is sent val largeFile = new java.io.File("video.mp4") requests.post("https://api.example.com/upload", data = largeFile) ``` -------------------------------- ### Client Certificates with Password Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Provide a password for a password-protected PKCS 12 archive when making a GET request. This is useful for secure client authentication. ```scala requests.get( "https://client.badssl.org", cert = ("./badssl.com-client.p12", "password") ) ``` -------------------------------- ### Package-Level Convenience Functions for HTTP Methods Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/requester.md These functions provide easy access to common HTTP methods like GET, POST, PUT, DELETE, HEAD, OPTIONS, and PATCH. They are available at the package level for direct use. ```Scala // These are available at the package level: requests.get(url, ...) // GET requests requests.post(url, ...) // POST requests requests.put(url, ...) // PUT requests requests.delete(url, ...) // DELETE requests requests.head(url, ...) // HEAD requests requests.options(url, ...) // OPTIONS requests requests.patch(url, ...) // PATCH requests (unofficial) ``` -------------------------------- ### Catch and Handle Specific Exceptions Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/errors.md Provides a comprehensive example of catching various Requests Scala exceptions, including UnknownHostException, TimeoutException, InvalidCertException, RequestFailedException, and generic RequestsException. ```scala try { val response = requests.get("https://api.example.com/data") println("Success: " + response.text()) } catch { case e: UnknownHostException => println(s"Network issue: cannot reach ${e.host}") case e: TimeoutException => println(s"Request timed out after ${e.readTimeout}ms") case e: InvalidCertException => println(s"SSL error: ${e.cause.getMessage}") case e: RequestFailedException => println(s"HTTP ${e.response.statusCode}: ${e.response.text()}") case e: RequestsException => println(s"Other requests error: ${e.message}") } ``` -------------------------------- ### Creating a Session with Default Configuration Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Shows how to initialize a session with default headers, timeouts, and cookie persistence settings for subsequent requests. ```scala val apiSession = requests.Session( headers = Map("Authorization" -> "Bearer token123"), readTimeout = 30000, connectTimeout = 5000, persistCookies = true ) try { val r1 = apiSession.get("https://api.example.com/users") val r2 = apiSession.post("https://api.example.com/data", data = Map("key" -> "value")) } finally { apiSession.close() } ``` -------------------------------- ### Client Certificates (Mutual TLS) - PKCS12 Without Password Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/authentication-ssl.md Use PKCS12 client certificates for mutual TLS authentication. This example shows how to provide a PKCS12 file path without a password, relying on implicit conversion. ```scala val response = requests.get( "https://client-cert.example.com", cert = "./client.p12" // Implicit conversion ) ``` -------------------------------- ### Demonstrate Configuration Precedence Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/configuration.md Illustrates how configuration values are resolved, with per-request parameters having the highest precedence, followed by session defaults, and then package-level defaults. ```scala // Example: resolving readTimeout // Package default is 10000ms requests.get("https://api.example.com") // Uses 10000ms // Session overrides package val session = Session(readTimeout = 20000) session.get("https://api.example.com") // Uses 20000ms // Request overrides session session.get( "https://api.example.com", readTimeout = 5000 ) // Uses 5000ms ``` -------------------------------- ### Configure and Use a Session Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/session.md Create a session with custom headers, authentication, and timeouts. All subsequent requests made with this session will use these configurations. ```scala val apiSession = Session( headers = Map( "User-Agent" -> "MyApp/1.0", "Accept" -> "application/json" ), auth = RequestAuth.Bearer("eyJ0eXAiOiJKV1QiLCJhbGc..."), readTimeout = 30000, // 30 seconds connectTimeout = 5000, // 5 seconds maxRedirects = 10, persistCookies = true ) try { // All requests use the configured defaults val users = apiSession.get("https://api.example.com/users") val user = apiSession.get("https://api.example.com/users/123") val created = apiSession.post( "https://api.example.com/users", data = Map("name" -> "Alice", "email" -> "alice@example.com") ) } finally { apiSession.close() } ``` -------------------------------- ### Building and Executing a Request Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-config.md Demonstrates how to construct a Request object with specific headers and max redirects, then execute it using a POST request with data. Ensure the Request object is created before calling the execution method. ```scala // Build a request configuration val req = Request( url = "https://api.example.com/users", headers = Seq("Authorization" -> "Bearer token123"), maxRedirects = 3 ) // Execute it with a POST body val response = requests.post(req, data = Map("name" -> "Alice")) // Or execute with a GET (no body) val response2 = requests.get(req, data = RequestBlob.EmptyRequestBlob) ``` -------------------------------- ### Session Management and Cookie Handling Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Demonstrates creating a session, making requests, and how cookies are automatically handled and persisted. Remember to close the session after use to prevent resource leaks. ```scala val s = requests.Session() val r = s.get("https://httpbin.org/cookies/set?freeform=test") val r2 = s.get("https://httpbin.org/cookies") r2.text() // {"cookies":{"freeform":"test"}} s.close() // Don't forget to close the session! ``` -------------------------------- ### GET Request with Error Handling Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/requester.md Demonstrates making a GET request with error checking disabled and handling potential non-200 status codes. ```scala // With error handling val resp = requests.get( "https://api.example.com/data", check = false ) if (resp.statusCode == 200) { println(resp.text()) } else { println(s"Error: ${resp.statusCode}") } ``` -------------------------------- ### Proper Resource Cleanup with Session Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/REFERENCE.md Shows the recommended pattern for using a Session and ensuring its resources are properly released using a try-finally block. ```scala val session = Session() try { // Make requests... } finally { session.close() // Release all resources } ``` -------------------------------- ### Akka-HTTP Basic GET Request Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Shows a basic GET request using Akka-HTTP, requiring ActorSystem, ActorMaterializer, and ExecutionContext. Handles responses asynchronously with Futures. ```scala import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.stream.ActorMaterializer import scala.concurrent.Future import scala.util.{ Failure, Success } implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() // needed for the future flatMap/onComplete in the end implicit val executionContext = system.dispatcher val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "http://akka.io")) responseFuture .onComplete { case Success(res) => println(res) case Failure(_) => sys.error("something wrong") } ``` -------------------------------- ### POST Request with Configuration and Data Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-config.md Shows how to execute a POST request using a pre-configured Request object, including authentication and custom headers. The request body is provided as a Map. ```scala val req = Request( url = "https://api.example.com/users", auth = ("admin", "password"), headers = Seq("X-Request-ID" -> "12345") ) val response = requests.post( req, data = Map("name" -> "Bob", "email" -> "bob@example.com"), chunkedUpload = false ) ``` -------------------------------- ### Using Sessions for Persistent Requests Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Demonstrates how to use sessions to automatically persist cookies and reuse configurations across multiple requests. Remember to close the session when done. ```scala val session = requests.Session() try { // Cookies automatically persisted val r1 = session.get("https://httpbin.org/cookies/set?token=xyz") val r2 = session.get("https://httpbin.org/cookies") // Token included // Reuse configuration val r3 = session.post("https://api.example.com/data", data = Map("key" -> "value")) } finally { session.close() // Release resources } ``` -------------------------------- ### EmptyRequestBlob Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Represents a request with no body, typically used for GET and HEAD requests. It sets the Content-Length to 0. ```APIDOC ## EmptyRequestBlob ### Description Used for requests that do not require a request body, such as GET or HEAD requests. It ensures the `Content-Length` header is set to `0`. ### Usage This is often handled automatically by the library for appropriate HTTP methods. It can also be used explicitly when needed. ### Example ```scala // Automatic for GET requests val response = requests.get("https://api.example.com/data") // Explicit for other methods val response = requests.head("https://api.example.com") ``` ``` -------------------------------- ### EmptyRequestBlob Object Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Represents a request with no body, typically used for GET and HEAD requests. It sets Content-Length to 0. ```Scala object EmptyRequestBlob extends RequestBlob { def write(out: java.io.OutputStream): Unit = () override def headers = Seq("Content-Length" -> "0") } ``` -------------------------------- ### Accessing Content Type Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/response.md Gets the MIME type of the response content from the Content-Type header. Returns an Option[String]. ```scala val response = requests.get("https://api.github.com/events") response.contentType // Some("application/json; charset=utf-8") ``` -------------------------------- ### Handle StreamHeaders in Streaming Request Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/response.md Example of using StreamHeaders in a streaming request, checking status and processing the response stream. ```scala var headers: StreamHeaders = null requests.get.stream( "https://api.example.com/large-file.json", onHeadersReceived = h => { headers = h if (!h.is2xx) { println(s"Error response: ${h.statusCode}") } } ).readBytesThrough { inputStream => // Process streaming response } ``` -------------------------------- ### Profile Request Performance Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/REFERENCE.md Measure the time taken for a single HTTP GET request. This is useful for basic performance profiling. ```scala val start = System.currentTimeMillis() val response = requests.get("https://api.example.com") val elapsed = System.currentTimeMillis() - start println(s"Request took ${elapsed}ms") ``` -------------------------------- ### Multiple Authentication Methods for Different Services Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/authentication-ssl.md Demonstrates setting up separate sessions for different services, each with its own authentication method: Basic auth, Bearer token, client certificate with Bearer token, and no authentication for public APIs. ```scala // Service 1: Basic auth val basicService = Session( auth = RequestAuth.Basic("user1", "pass1") ) // Service 2: Bearer token val tokenService = Session( auth = RequestAuth.Bearer("token_xyz") ) // Service 3: Client certificate val certService = Session( cert = ("./client.p12", "password"), auth = RequestAuth.Bearer("api_token") // Both cert and token ) // Service 4: No auth (public API) val publicService = Session( auth = RequestAuth.Empty ) ``` -------------------------------- ### Form-Encoded Data Example Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Demonstrates sending form-encoded data using a Map or a sequence of tuples. The Content-Type is automatically set to application/x-www-form-urlencoded. ```Scala val response = requests.post( "https://api.example.com/login", data = Map("username" -> "alice", "password" -> "secret123") ) // Also works with tuples val response = requests.post( "https://api.example.com/data", data = Seq(("key1", "value1"), ("key2", "value2")) ) ``` -------------------------------- ### Make Various HTTP Requests Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Shows how to perform different HTTP methods like POST, PUT, DELETE, HEAD, and OPTIONS using the requests library. It also demonstrates dynamically choosing the HTTP method. ```scala val r = requests.post("http://httpbin.org/post", data = Map("key" -> "value")) val r = requests.put("http://httpbin.org/put", data = Map("key" -> "value")) val r = requests.delete("http://httpbin.org/delete") val r = requests.head("http://httpbin.org/head") val r = requests.options("http://httpbin.org/get") // dynamically choose what HTTP method to use val r = requests.send("put")("http://httpbin.org/put", data = Map("key" -> "value")) ``` -------------------------------- ### Configure PKCS12 Certificate with Password Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/types.md Use this when your PKCS12 certificate file is protected by a password. It demonstrates how to provide both the certificate path and its password. ```scala val response = requests.get( "https://client.badssl.com", cert = ("./client.p12", "password123") ) ``` -------------------------------- ### Setting Read and Connection Timeouts Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Shows how to configure read timeouts (for receiving data) and connection timeouts (for establishing the connection) for HTTP requests. ```scala // Read timeout (waiting for response data) val response = requests.get( "https://api.example.com/slow", readTimeout = 30000 // 30 seconds ) ``` ```scala // Connection timeout (establishing connection) val response = requests.get( "https://api.example.com", connectTimeout = 5000 // 5 seconds ) ``` ```scala // Both val response = requests.get( "https://api.example.com", readTimeout = 30000, connectTimeout = 5000 ) ``` -------------------------------- ### Creating MultiItems for Multipart Uploads Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Demonstrates how to create `MultiItem` instances for different data types within a multipart upload. This includes string values, file uploads with a specified filename, byte arrays, and NIO paths. ```scala // String value requests.MultiItem("username", "alice") ``` ```scala // File upload requests.MultiItem("avatar", new java.io.File("avatar.png"), "avatar.png") ``` ```scala // Byte array requests.MultiItem("data", Array[Byte](1, 2, 3, 4)) ``` ```scala // Path requests.MultiItem("document", java.nio.file.Paths.get("report.pdf"), "report.pdf") ``` -------------------------------- ### POST Request with Deflate Compression Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Example of sending a byte array request body compressed using Deflate. This is an alternative compression method to Gzip. ```scala requests.post( "https://api.example.com/upload", data = Array[Byte](1, 2, 3, ...), compress = requests.Compress.Deflate ) ``` -------------------------------- ### Stream and Parse JSON Data Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/requester.md This example demonstrates how to stream JSON data from a URL and parse it using ujson. This is efficient for large JSON responses. ```scala // Stream with ujson parsing val json = ujson.read(requests.get.stream("https://api.github.com/repos")) ``` -------------------------------- ### Configure Proxy for Requests Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/configuration.md Set up proxy servers for outgoing HTTP requests. Supports basic proxying and proxy authentication. ```scala // No proxy (default) val response = requests.get("https://api.example.com") ``` ```scala // Use proxy val response = requests.get( "https://api.example.com", proxy = ("proxy.corp.com", 8080) ) ``` ```scala // Proxy with authentication val response = requests.get( "https://api.example.com", proxy = ("proxy.corp.com", 8080), auth = RequestAuth.Proxy("proxyuser", "proxypass") ) ``` ```scala // Session-level proxy val session = Session( proxy = ("proxy.corp.com", 8080) ) val response = session.get("https://api.example.com") ``` -------------------------------- ### requests.get.stream Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-config.md Executes a streaming GET request using a pre-configured `Request` object. Allows processing data as it arrives and provides a callback for received headers. ```APIDOC ## GET Request Streaming ### Description Executes a streaming GET request with the configuration from the `Request` object. This is useful for large responses where you want to process data incrementally. It allows for a callback to be executed when headers are received. ### Method GET ### Endpoint (Determined by the `url` in the `Request` object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (RequestBlob) - Required - The data to send in the request body (typically `RequestBlob.EmptyRequestBlob` for GET requests). - **chunkedUpload** (Boolean) - Optional - If true, enables chunked upload (less common for GET). - **onHeadersReceived** (StreamHeaders => Unit) - Optional - A callback function executed when response headers are received. ### Request Example ```scala val req = Request( url = "https://api.example.com/large-file", readTimeout = 30000 ) requests.get.stream( req, data = RequestBlob.EmptyRequestBlob, chunkedUpload = false, onHeadersReceived = null ).readBytesThrough { inputStream => // Process streaming data } ``` ### Response #### Success Response Returns a `geny.Writable` which can be used to read the streaming response body. #### Response Example (The `readBytesThrough` block processes the streaming data) ``` -------------------------------- ### Usage of Proxy Authentication Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/authentication-ssl.md Shows how to configure and use proxy authentication for direct requests and within sessions. ```scala val response = requests.get( "https://api.example.com", proxy = ("proxy.corp.com", 8080), auth = RequestAuth.Proxy("proxyuser", "proxypass") ) // Session with corporate proxy val session = Session( proxy = ("proxy.corp.com", 8080), auth = RequestAuth.Proxy("domain\username", "password") ) val response = session.get("https://api.example.com") ``` -------------------------------- ### Handle Expired Client Certificate Error Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/authentication-ssl.md This example demonstrates catching an `InvalidCertException` specifically for expired client certificates. It advises renewing the certificate and updating its path. ```scala try { requests.get( "https://api.example.com", cert = ("./expired-client.p12", "password") ) } catch { case e: InvalidCertException => println("Client certificate has expired") println("Renew certificate and update path") } ``` -------------------------------- ### Proxy Configuration Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Configure a proxy server for requests. Supports basic authentication for the proxy. ```scala val response = requests.get( "https://api.example.com", proxy = ("proxy.corp.com", 8080) ) ``` ```scala // With authentication val response = requests.get( "https://api.example.com", proxy = ("proxy.corp.com", 8080), auth = RequestAuth.Proxy("user", "pass") ) ``` -------------------------------- ### Efficient vs. Inefficient Session Usage Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/session.md Demonstrates efficient session reuse for multiple requests versus inefficient creation of new HTTP clients for each request due to varying configurations like connectTimeout. ```scala // Efficient: reuses HttpClient val session = Session() for (i <- 1 to 1000) { session.get(s"https://api.example.com/item/$i") } session.close() // Inefficient: creates new HttpClient for each request for (i <- 1 to 1000) { requests.get( s"https://api.example.com/item/$i", connectTimeout = i * 100 // Different timeout each time! ) } ``` -------------------------------- ### Send Custom HTTP Headers Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Configure custom HTTP headers for a GET request. This is useful for setting user agents, authentication tokens, or other request-specific metadata. ```Scala requests.get( "https://api.github.com/some/endpoint", headers = Map("user-agent" -> "my-app/0.0.1") ) ``` -------------------------------- ### Creating and Modifying Request Variants Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-config.md Demonstrates building a base Request configuration and then creating modified versions (variants) using the `copy` method for different URLs and headers. These variants can then be executed. ```scala // Base configuration val baseRequest = Request( url = "https://api.example.com", auth = RequestAuth.Bearer("token"), headers = Seq( "Accept" -> "application/json", "User-Agent" -> "MyApp/1.0" ), readTimeout = 20000 ) // Create variants by copying val userRequest = baseRequest.copy( url = baseRequest.url + "/users" ) val postRequest = baseRequest.copy( url = baseRequest.url + "/users", headers = baseRequest.headers ++ Seq("Content-Type" -> "application/json") ) // Execute variants val users = requests.get(userRequest, RequestBlob.EmptyRequestBlob, false) val created = requests.post(postRequest, Map("name" -> "Alice"), false) ``` -------------------------------- ### Get HTTP Response Raw Byte Contents Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Retrieve the raw byte contents of an HTTP response. This is useful for handling binary data such as images or files. ```Scala r.contents // Array(91, 123, 34, 105, 100, 34, 58, 34, 55, 57, 57, 48, 48, 54, 49, ... ``` -------------------------------- ### Access Response Headers Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/response.md Demonstrates how to access response headers, including single values, all values for a header, and checking for header existence. ```scala val response = requests.get("https://api.example.com") // Access single header value val contentType = response.headers("content-type").headOption // Some("application/json; charset=utf-8") // Access all values for a header val setCookies = response.headers.get("set-cookie").getOrElse(Seq()) // Check if header exists if (response.headers.contains("x-custom-header")) { println(response.headers("x-custom-header").head } ``` -------------------------------- ### Get HTTP Response Text Content Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Access the text content of an HTTP response. This is useful for retrieving human-readable data like HTML or JSON strings. ```Scala r.text() // ["id":"7990061484","type":"PushEvent","actor":{"id":6242317,"login":... ``` -------------------------------- ### Importing Specific Public Types Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/REFERENCE.md Demonstrates how to import specific types from the requests package for more granular control. ```scala // Or explicit imports import requests.Requester import requests.Session import requests.Response import requests.Request import requests.RequestAuth import requests.RequestBlob import requests.Compress import requests.Cert import requests.TimeoutException import requests.UnknownHostException import requests.InvalidCertException import requests.RequestFailedException import requests.RequestsException ``` -------------------------------- ### Create a Default Session Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/configuration.md Configure default headers, authentication, and timeouts for all requests made through this session. Useful for setting common options like User-Agent or API tokens. ```scala val apiSession = Session( headers = Map( "User-Agent" -> "MyApp/1.0", "Accept" -> "application/json", "Accept-Language" -> "en-US" ), auth = RequestAuth.Bearer("token_xyz"), readTimeout = 30000, connectTimeout = 10000, persistCookies = true, maxRedirects = 10 ) // All requests use these defaults val response = apiSession.get("https://api.example.com/users") ``` -------------------------------- ### Get HTTP Response Status Code and Headers Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Retrieve the status code and headers from an HTTP response. The status code is an integer, and headers are returned as a buffer of strings. ```Scala val r = requests.get("https://api.github.com/events") r.statusCode // 200 r.headers("content-type") // Buffer("application/json; charset=utf-8") ``` -------------------------------- ### Usage of Basic Authentication Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/authentication-ssl.md Shows how to use Basic Authentication with requests-scala, including implicit tuple conversion and explicit class instantiation. ```scala // Using tuple (implicit conversion) val response = requests.get( "https://api.github.com/user", auth = ("octocat", "gh_token_secret") ) // Explicit Basic authentication val response = requests.get( "https://api.example.com/protected", auth = RequestAuth.Basic("user@example.com", "password123") ) // Session-level basic auth val session = Session( auth = RequestAuth.Basic("admin", "secret") ) val response = session.get("https://admin.example.com/dashboard") ``` -------------------------------- ### Build and Test Requests-Scala Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/REFERENCE.md Commands to build the JAR assembly and run tests for the Requests-Scala project using the Mill build tool. ```bash cd requests-scala ./mill requests.jvm[2.13].test # Run tests ./mill show requests.jvm[2.13].assembly # Build JAR ``` -------------------------------- ### Geny Writable Body Examples Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Illustrates using types that implement geny.Writable as request bodies, including ujson.Value, upickle.default.writable, and scalatags.Text.TypedTag. The library automatically infers Content-Type and Content-Length. ```Scala // ujson values requests.post( "https://api.example.com/data", data = ujson.Obj("user" -> "alice", "age" -> 30) ) // upickle serialization case class User(name: String, email: String) val user = User("alice", "alice@example.com") requests.post( "https://api.example.com/users", data = upickle.default.writable(user) ) // scalatags HTML requests.post( "https://api.example.com/render", data = html( head(title("Hello")), body(h1("World")) ) ) ``` -------------------------------- ### Chain Streaming Requests Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Send a streaming GET request and pipe its output directly as the data payload for a streaming POST request. This enables efficient data transfer between requests. ```Scala os.write( os.pwd / "chained.json", requests.post.stream( "https://httpbin.org/post", data = requests.get.stream("https://api.github.com/events") ) ) ``` -------------------------------- ### Configure PKCS12 Certificate using Explicit P12 Object Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/types.md Use this to explicitly create a `Cert.P12` object when providing a PKCS12 certificate with a password. This offers a more type-safe approach. ```scala val response = requests.get( "https://client.badssl.com", cert = Cert.P12("./client.p12", Some("password123")) ) ``` -------------------------------- ### Conditional Requests with ETag Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/quick-reference.md Performs a conditional GET request using the `If-None-Match` header with an ETag value obtained from a previous response. A 304 status code indicates the resource has not changed. ```scala val response1 = requests.get("https://api.example.com/data") val etag = response1.headers.get("etag").flatMap(_.headOption) // Use ETag for conditional request val response2 = requests.get( "https://api.example.com/data", headers = etag.map("If-None-Match" -> _).toMap ) // 304 Not Modified means data unchanged if (response2.statusCode == 304) { println("Data not modified, using cached version") } else { println("Data updated: " + response2.text()) } ``` -------------------------------- ### Streaming Request Body from One Request to Another Source: https://github.com/com-lihaoyi/requests-scala/blob/master/_autodocs/api-reference/request-body.md Demonstrates how to stream data from a GET request directly into the body of a POST request using `requests.get.stream` and `requests.post.stream`. The output is written to a file. ```scala // Stream data from one request to another os.write( os.pwd / "output.json", requests.post.stream( "https://api.example.com/process", data = requests.get.stream("https://api.example.com/source") ) ) ``` -------------------------------- ### Client Certificates with SSL Verification Disabled Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Use this snippet to make a GET request with a client certificate and disable SSL certificate verification. This is typically used in test environments with self-signed certificates. ```scala requests.get( "https://client.badssl.com", cert = ("./badssl.com-client.p12", "password"), verifySslCerts = false ) ``` -------------------------------- ### Set Connect Timeout for HTTP Requests Source: https://github.com/com-lihaoyi/requests-scala/blob/master/readme.md Demonstrates setting a connect timeout for HTTP requests. If the client cannot establish a connection to the server within the specified time, a TimeoutException is thrown. ```Scala requests.get("https://httpbin.org/delay/1", connectTimeout = 10) // TimeoutException requests.get("https://httpbin.org/delay/1", connectTimeout = 1500) // ok requests.get("https://httpbin.org/delay/3", connectTimeout = 1500) // ok ```