### HTTP Methods - Function Style (F#)
Source: https://context7.com/fsprojects/fshttp/llms.txt
Illustrates using top-level convenience functions like `get` and `post` for making HTTP requests, with examples of piping configuration and response transformations.
```APIDOC
## Simple GET Request
### Description
Performs a simple GET request and returns the response as text.
### Method
GET
### Endpoint
https://reqres.in/api/users
### Response
Success Response (200)
- (Response body as text)
## GET Request with Configuration and JSON Response
### Description
Performs a GET request with a configured timeout and parses the response as JSON.
### Method
GET
### Endpoint
https://reqres.in/api/users
### Parameters
#### Query Parameters
- **page** (string) - Optional - The page number to retrieve.
### Request Example
```fsharp
get "https://reqres.in/api/users"
|> Config.timeoutInSeconds 30.0
|> Request.send
|> Response.toJson
|> fun json -> json?page.GetInt32()
```
### Response
Success Response (200)
- **page** (integer) - The current page number from the JSON response.
```
--------------------------------
### Install FsHttp via NuGet
Source: https://context7.com/fsprojects/fshttp/llms.txt
Reference FsHttp from NuGet in an F# script or project.
```fsharp
// F# script
#r "nuget: FsHttp"
open FsHttp
```
```xml
```
--------------------------------
### F# HTTP POST Request Example
Source: https://github.com/fsprojects/fshttp/blob/master/README.md
Example of making a POST request with a JSON body and setting the Cache-Control header in F#.
```fsharp
#r "nuget: FsHttp"
open FsHttp
http {
POST "https://reqres.in/api/users"
CacheControl "no-cache"
body
jsonSerialize
{|
name = "morpheus"
job = "leader"
|}
}
|> Request.send
```
--------------------------------
### C# HTTP POST Request Example
Source: https://github.com/fsprojects/fshttp/blob/master/README.md
Example of making a POST request with a JSON body and setting the Cache-Control header in C#.
```csharp
#r "nuget: FsHttp"
using FsHttp;
await Http
.Post("https://reqres.in/api/users")
.CacheControl("no-cache")
.Body()
.JsonSerialize(new
{
name = "morpheus",
job = "leader"
}
)
.SendAsync();
```
--------------------------------
### HTTP Methods using F# Function Style
Source: https://context7.com/fsprojects/fshttp/llms.txt
Shows simple GET requests using top-level convenience functions and adding configuration via piping.
```fsharp
// Simple GET
get "https://reqres.in/api/users"
|> Request.send
|> Response.toText
```
```fsharp
// With piped configuration added after construction
get "https://reqres.in/api/users"
|> Config.timeoutInSeconds 30.0
|> Request.send
|> Response.toJson
|> fun json -> json?page.GetInt32() // dynamic JSON access via ? operator
// => 1
```
--------------------------------
### HTTP Methods using C# Fluent API
Source: https://context7.com/fsprojects/fshttp/llms.txt
Demonstrates GET and POST requests with a JSON body using the C# fluent API extension methods.
```csharp
using FsHttp;
// GET
var response = await Http
.Get("https://reqres.in/api/users")
.SendAsync();
// POST with JSON body
var created = await Http
.Post("https://reqres.in/api/users")
.CacheControl("no-cache")
.Body()
.JsonSerialize(new { name = "morpheus", job = "leader" })
.SendAsync();
var json = await created.ToJsonAsync();
```
--------------------------------
### HTTP Methods using F# Computation Expression
Source: https://context7.com/fsprojects/fshttp/llms.txt
Demonstrates GET, POST, PUT, DELETE, and PATCH requests using the FsHttp computation expression DSL.
```fsharp
// GET
http {
GET "https://reqres.in/api/users?page=2"
CacheControl "no-cache"
}
|> Request.send
```
```fsharp
// POST
http {
POST "https://reqres.in/api/users"
body
jsonSerialize {| name = "morpheus"; job = "leader" |}
}
|> Request.send
```
```fsharp
// PUT
http {
PUT "https://reqres.in/api/users/2"
body
jsonSerialize {| name = "morpheus"; job = "zion resident" |}
}
|> Request.send
```
```fsharp
// DELETE
http {
DELETE "https://reqres.in/api/users/2"
}
|> Request.send
```
```fsharp
// PATCH
http {
PATCH "https://reqres.in/api/users/2"
body
jsonSerialize {| name = "morpheus" |}
}
|> Request.send
```
--------------------------------
### HTTP Methods - Computation Expression (F#)
Source: https://context7.com/fsprojects/fshttp/llms.txt
Demonstrates how to use FsHttp's computation expression (CE) DSL (`http { ... }`) to make GET, POST, PUT, DELETE, and PATCH requests.
```APIDOC
## GET Request
### Description
Sends a GET request to the specified URL.
### Method
GET
### Endpoint
https://reqres.in/api/users?page=2
### Request Body
None
### Response
Success Response (200)
- (Content of the response)
## POST Request
### Description
Sends a POST request with a JSON body to the specified URL.
### Method
POST
### Endpoint
https://reqres.in/api/users
### Request Body
- **name** (string) - Required - The name for the user.
- **job** (string) - Required - The job title for the user.
### Request Example
```fsharp
http {
POST "https://reqres.in/api/users"
body
jsonSerialize {| name = "morpheus"; job = "leader" |}
}
|> Request.send
```
### Response
Success Response (200)
- (Content of the response, typically the created resource)
## PUT Request
### Description
Sends a PUT request with a JSON body to update a resource at the specified URL.
### Method
PUT
### Endpoint
https://reqres.in/api/users/2
### Request Body
- **name** (string) - Required - The updated name for the user.
- **job** (string) - Required - The updated job title for the user.
### Request Example
```fsharp
http {
PUT "https://reqres.in/api/users/2"
body
jsonSerialize {| name = "morpheus"; job = "zion resident" |}
}
|> Request.send
```
### Response
Success Response (200)
- (Content of the response, typically the updated resource)
## DELETE Request
### Description
Sends a DELETE request to the specified URL to remove a resource.
### Method
DELETE
### Endpoint
https://reqres.in/api/users/2
### Request Body
None
### Response
Success Response (200 or 204)
- (Typically no content for a successful deletion)
## PATCH Request
### Description
Sends a PATCH request with a JSON body to partially update a resource at the specified URL.
### Method
PATCH
### Endpoint
https://reqres.in/api/users/2
### Request Body
- **name** (string) - Required - The updated name for the user.
### Request Example
```fsharp
http {
PATCH "https://reqres.in/api/users/2"
body
jsonSerialize {| name = "morpheus" |}
}
|> Request.send
```
### Response
Success Response (200)
- (Content of the response, typically the updated resource)
```
--------------------------------
### HTTP Methods - C# Fluent API
Source: https://context7.com/fsprojects/fshttp/llms.txt
Shows how to use FsHttp's fluent API in C# for making asynchronous HTTP requests, including GET and POST with JSON bodies.
```APIDOC
## GET Request (C#)
### Description
Sends an asynchronous GET request using the C# fluent API.
### Method
GET
### Endpoint
https://reqres.in/api/users
### Response
Success Response (200)
- (The HTTP response object)
## POST Request with JSON Body (C#)
### Description
Sends an asynchronous POST request with a JSON body using the C# fluent API.
### Method
POST
### Endpoint
https://reqres.in/api/users
### Request Body
- **name** (object) - Required - An anonymous object representing the JSON payload.
- **job** (object) - Required - An anonymous object representing the JSON payload.
### Request Example
```csharp
await Http.Post("https://reqres.in/api/users")
.CacheControl("no-cache")
.Body()
.JsonSerialize(new { name = "morpheus", job = "leader" })
.SendAsync();
```
### Response
Success Response (200)
- (The HTTP response object, typically representing the created resource)
```
--------------------------------
### Process JSON Response Asynchronously
Source: https://github.com/fsprojects/fshttp/blob/master/docu-TODOs.md
This snippet shows how to send an asynchronous request, process the response content as JSON, and then map the JSON data to specific values. 'sendAsync' sends the request immediately, while 'toAsync' builds a request that needs to be started.
```F#
let asyncResponse =
// Assume this returns: { "name": "Paul"; "age": 54 }
http {
GET "https://mysite"
AcceptLanguage "en-US"
}
|> Request.sendAsync
|> Async.await Response.toJsonAsync
|> Async.map (fun json -> json?name.GetString(), json?age.GetInt32())
```
--------------------------------
### Configure Proxy for Requests
Source: https://context7.com/fsprojects/fshttp/llms.txt
Set up proxy servers for HTTP requests, including options for basic authentication. Proxies can be configured inline within the computation expression or via pipe-style chaining.
```fsharp
open FsHttp
open System.Net
// Simple proxy
get "https://reqres.in/api/users"
|> Config.proxy "http://proxy.internal:8080"
|> Request.send
// Proxy with credentials
get "https://reqres.in/api/users"
|> Config.proxyWithCredentials "http://proxy.internal:8080" (NetworkCredential("user","pass"))
|> Request.send
// Inside the CE
http {
config_proxy "http://proxy.internal:8080"
GET "https://reqres.in/api/users"
}
|> Request.send
```
--------------------------------
### Create Reusable HTTP Builders with Base URL and Headers
Source: https://context7.com/fsprojects/fshttp/llms.txt
Define a base HTTP client configuration including base URL and authorization headers, then derive specific requests from it. This promotes code reuse and consistency.
```fsharp
open FsHttp
open FsHttp.Operators // for <>
// Build a reusable builder with base URL + auth
let myApi =
http {
config_useBaseUrl "https://reqres.in"
AuthorizationBearer "my-token"
CacheControl "no-cache"
}
// Derive specific requests from the base builder
let users = myApi { GET "/api/users" } |> Request.send
let user1 = myApi { GET "/api/users/1" } |> Request.send
```
--------------------------------
### Query Parameters in FsHttp
Source: https://context7.com/fsprojects/fshttp/llms.txt
Illustrates adding query parameters to a URL, both inline within the URL string and as a structured list.
```fsharp
// Inline URL with line-break formatting and commented-out parameter
http {
GET "https://reqres.in/api/users
?page=2
//&skip=5 <- this line is ignored
&per_page=10"
}
|> Request.send
```
```fsharp
// Structured query list (preferred for dynamic values)
http {
GET "https://reqres.in/api/users"
query [
"page", "2"
"per_page", "10"
"delay", "1"
]
}
|> Request.send
|> Response.toJson
|> fun json -> json?total.GetInt32()
// => 12
```
--------------------------------
### Synchronous and Asynchronous Request Sending
Source: https://context7.com/fsprojects/fshttp/llms.txt
Demonstrates sending requests synchronously (blocking) and asynchronously using F# async workflows or .NET Tasks.
```fsharp
open FsHttp
let req =
http {
GET "https://reqres.in/api/users"
CacheControl "no-cache"
}
// Synchronous (blocks the calling thread)
let response = req |> Request.send
// F# async workflow
let asyncResult =
async {
let! response = req |> Request.sendAsync
return response |> Response.toJson
}
// .NET Task (C# interop / Async.StartAsTask)
let task = req |> Request.sendTAsync
```
--------------------------------
### Send Async Request with Method-First Function
Source: https://github.com/fsprojects/fshttp/blob/master/docu-TODOs.md
Use this syntax for sending asynchronous requests, especially when the HTTP method is known upfront. Requires `Request.sendAsync`.
```F#
get "https://mysite" {
AcceptLanguage "en-US"
}
|> Request.sendAsync
```
--------------------------------
### Request Headers in FsHttp
Source: https://context7.com/fsprojects/fshttp/llms.txt
Shows how to set standard and custom request headers using FsHttp's computation expression DSL.
```fsharp
open FsHttp
http {
GET "https://api.github.com/repos/fsprojects/FsHttp/issues"
// Standard named operations
AuthorizationBearer "ghp_yourTokenHere"
Accept "application/vnd.github.v3+json"
UserAgent "FsHttp/15.0.3"
CacheControl "no-cache"
// Basic auth shorthand
// AuthorizationUserPw "user" "pass"
// Custom / non-standard header
header "X-GitHub-Api-Version" "2022-11-28"
}
|> Request.send
|> Response.toJson
|> fun json -> json.EnumerateArray() |> Seq.map (fun i -> i?title.GetString()) |> Seq.toList
```
--------------------------------
### Save Response to File
Source: https://context7.com/fsprojects/fshttp/llms.txt
Download response content and save it directly to a file on the local filesystem. Supports both synchronous and asynchronous operations.
```fsharp
open FsHttp
// Downloads a NuGet package and saves it as a zip file
get "https://www.nuget.org/api/v2/package/FsHttp/15.0.3"
|> Request.send
|> Response.saveFile @"/tmp/FsHttp.zip"
// Async variant
async {
let! response =
get "https://www.nuget.org/api/v2/package/FsHttp/15.0.3"
|> Request.sendAsync
do! response |> Response.saveFileAsync "/tmp/FsHttp.zip"
}
```
--------------------------------
### Request Headers
Source: https://context7.com/fsprojects/fshttp/llms.txt
Details how to set standard and custom request headers, including authentication and content-type headers.
```APIDOC
## Setting Request Headers
### Description
Demonstrates setting various standard and custom HTTP headers for a request.
### Method
GET
### Endpoint
https://api.github.com/repos/fsprojects/FsHttp/issues
### Parameters
#### Request Headers
- **AuthorizationBearer** (string) - Optional - Sets the Bearer token for authentication.
- **Accept** (string) - Optional - Specifies the desired response format.
- **UserAgent** (string) - Optional - Identifies the client making the request.
- **CacheControl** (string) - Optional - Directives for caching behavior.
- **AuthorizationUserPw** (string, string) - Optional - Shorthand for Basic Authentication.
- **header** (string, string) - Optional - Sets an arbitrary custom header.
### Request Example
```fsharp
http {
GET "https://api.github.com/repos/fsprojects/FsHttp/issues"
AuthorizationBearer "ghp_yourTokenHere"
Accept "application/vnd.github.v3+json"
UserAgent "FsHttp/15.0.3"
CacheControl "no-cache"
header "X-GitHub-Api-Version" "2022-11-28"
}
|> Request.send
```
### Response
Success Response (200)
- (A JSON array of issues, each with a 'title' field)
```
--------------------------------
### Multipart File Upload
Source: https://context7.com/fsprojects/fshttp/llms.txt
Perform multipart uploads with mixed content types. Use `multipart` to switch context and `textPart`, `filePart`, `binaryPart`, or `streamPart` for individual parts.
```fsharp
open FsHttp
// Mixed multipart upload
http {
POST "https://httpbin.org/post"
multipart
textPart "the-value-1" "field1" None
textPart "the-value-2" "field2" None
filePart "/tmp/report.pdf" None None // name and fileName inferred from path
binaryPart (System.IO.File.ReadAllBytes "img.png") "image" (Some "photo.png")
}
|> Request.send
|> Response.toJson
|> fun j -> j?files.GetPropertyNames()
```
--------------------------------
### Manually Compose URLs with > Operator
Source: https://context7.com/fsprojects/fshttp/llms.txt
Use the > operator for straightforward composition of URL path segments. This is useful when constructing URLs dynamically.
```fsharp
// Manual URL composition with the > operator
let baseUrl = "https://reqres.in"
let url = baseUrl > "api" > "users" > "1"
// => "https://reqres.in/api/users/1"
```
--------------------------------
### Send Request with ~% Operator Shorthand
Source: https://context7.com/fsprojects/fshttp/llms.txt
Utilize the ~% operator as a shorthand for `Request.send`. This simplifies the syntax for executing HTTP requests.
```fsharp
// ~% — send shorthand (equivalent to Request.send)
let response = % http { GET "https://reqres.in/api/users" }
```
--------------------------------
### Advanced Header Transformation for Staging Environment
Source: https://context7.com/fsprojects/fshttp/llms.txt
Implement a full header transformer to modify request headers, such as dynamically constructing the target URL for a staging environment. This allows for fine-grained control over request modification.
```fsharp
// Full header transformer for advanced scenarios
let stagingApi =
http {
config_transformHeader (fun (header: Header) ->
let address = "https://staging.reqres.in" > (header.target.address |> Option.defaultValue "")
{ header with target.address = Some address })
AuthorizationBearer "staging-token"
}
let! response = stagingApi { GET "/api/users" } |> Request.sendAsync
```
--------------------------------
### Query Parameters
Source: https://context7.com/fsprojects/fshttp/llms.txt
Explains how to add query parameters to requests, either by embedding them directly in the URL or using a structured list.
```APIDOC
## Query Parameters in URL
### Description
Embeds query parameters directly within the URL string, supporting line breaks and comments.
### Method
GET
### Endpoint
https://reqres.in/api/users?page=2&per_page=10
### Request Example
```fsharp
http {
GET "https://reqres.in/api/users\n ?page=2\n //&skip=5 <- this line is ignored\n &per_page=10"
}
|> Request.send
```
## Structured Query Parameters
### Description
Specifies query parameters as a typed list of key-value pairs, which is preferred for dynamic values.
### Method
GET
### Endpoint
https://reqres.in/api/users
### Parameters
#### Query Parameters
- **page** (string) - Optional - The page number.
- **per_page** (string) - Optional - The number of items per page.
- **delay** (string) - Optional - The delay in seconds.
### Request Example
```fsharp
http {
GET "https://reqres.in/api/users"
query [
"page", "2"
"per_page", "10"
"delay", "1"
]
}
|> Request.send
|> Response.toJson
|> fun json -> json?total.GetInt32()
```
### Response
Success Response (200)
- **total** (integer) - The total number of items available.
```
--------------------------------
### Send Binary, Stream, or File Content
Source: https://context7.com/fsprojects/fshttp/llms.txt
Send raw bytes, a stream, or a file's content directly as the request body.
```fsharp
open FsHttp
open System.IO
// Send raw bytes
let bytes = File.ReadAllBytes "image.png"
http {
POST "https://httpbin.org/post"
body
binary bytes
}
|> Request.send
```
```fsharp
// Send a stream
use fs = File.OpenRead "data.bin"
http {
POST "https://httpbin.org/post"
body
stream fs
}
|> Request.send
```
```fsharp
// Send file content directly
http {
POST "https://httpbin.org/post"
body
file "/tmp/report.pdf"
}
|> Request.send
```
--------------------------------
### Set Global Default Request Configuration
Source: https://context7.com/fsprojects/fshttp/llms.txt
Apply default configurations like timeouts and JSON serializer options to all subsequent requests by modifying `GlobalConfig.defaults`. Changes are inherited.
```fsharp
open FsHttp
// Set a global default timeout of 10 seconds
GlobalConfig.defaults
|> Config.timeoutInSeconds 10.0
|> GlobalConfig.set
// Set global JsonSerializerOptions (e.g. FSharp.SystemTextJson)
open System.Text.Json
open System.Text.Json.Serialization
FsHttp.GlobalConfig.Json.defaultJsonSerializerOptions <-
let opts = JsonSerializerOptions()
opts.Converters.Add(JsonFSharpConverter())
opts
```
--------------------------------
### Configure Request Timeout and Certificate Validation
Source: https://context7.com/fsprojects/fshttp/llms.txt
Set per-request configuration for timeouts and certificate validation. This can be done inline within the computation expression or using pipe-style chaining.
```fsharp
open FsHttp
// Inside the CE
http {
config_timeoutInSeconds 30.0
config_ignoreCertIssues
GET "https://self-signed.badssl.com/"
}
|> Request.send
// Pipe style (can be applied after construction, before sending)
get "https://reqres.in/api/users"
|> Config.timeoutInSeconds 15.0
|> Config.ignoreCertIssues
|> Request.send
// No timeout
get "https://reqres.in/api/users"
|> Config.noTimeout
|> Request.send
```
--------------------------------
### Combine URL Path Segments with > Operator
Source: https://context7.com/fsprojects/fshttp/llms.txt
Use the > operator to concatenate URL path segments. This provides a clean and readable way to build URLs.
```fsharp
// > — URL path segment combiner
let url = "https://api.example.com" > "v1" > "users" > "42"
// => "https://api.example.com/v1/users/42"
```
--------------------------------
### Expand Full Response Body in FSI Output
Source: https://context7.com/fsprojects/fshttp/llms.txt
Configure FsHttp to display the entire response body in the F# Interactive output. This is helpful for inspecting complete responses.
```fsharp
// Expand full response body in FSI output
http {
GET "https://reqres.in/api/users"
print_withResponseBodyExpanded
}
```
--------------------------------
### Send Synchronous Request with % Operator in FSI
Source: https://github.com/fsprojects/fshttp/blob/master/docu-TODOs.md
The `%` operator provides a concise syntax for sending synchronous requests in F# Interactive or notebooks. It blocks the caller thread, so use it only in interactive environments.
```F#
open FsHttp.Operators
% http {
GET "https://mysite"
AcceptLanguage "en-US"
}
```
--------------------------------
### Request Cancellation with CancellationToken
Source: https://context7.com/fsprojects/fshttp/llms.txt
Shows two methods for request cancellation: binding a `CancellationToken` within the computation expression or piping it after construction.
```fsharp
open FsHttp
open System.Threading
use cts = new CancellationTokenSource(timeout = System.TimeSpan.FromSeconds 5.0)
// Option A — bind in the CE
http {
GET "https://reqres.in/api/users?delay=10"
config_cancellationToken cts.Token
}
|> Request.send
```
```fsharp
// Option B — pipe after construction
get "https://reqres.in/api/users?delay=10"
|> Config.cancellationToken cts.Token
|> Request.send
```
--------------------------------
### Send Plain Text Request Body
Source: https://context7.com/fsprojects/fshttp/llms.txt
Send a plain text request body using the `text` keyword.
```fsharp
open FsHttp
http {
POST "https://httpbin.org/post"
body
text "Hello from FsHttp!"
}
|> Request.send
|> Response.toText
```
--------------------------------
### Specify Allowed Decompression Methods
Source: https://context7.com/fsprojects/fshttp/llms.txt
Control which decompression methods (e.g., GZip, Deflate) are automatically applied to responses. This allows for selective decompression.
```fsharp
// Choose specific methods
get "https://reqres.in/api/users"
|> Config.decompressionMethods [ DecompressionMethods.GZip ]
|> Request.send
```
--------------------------------
### Configure Request Timeout
Source: https://github.com/fsprojects/fshttp/blob/master/docu-TODOs.md
Set a specific timeout for a request using the `config_timeoutInSeconds` setting within the `http` block.
```F#
// A configuration per request
http {
config_timeoutInSeconds 10.0
}
```
--------------------------------
### Re-enable FSI Debug Logs
Source: https://context7.com/fsprojects/fshttp/llms.txt
Restore the default behavior of logging request/response details in F# Interactive. Use this if you previously disabled the logs.
```fsharp
// Re-enable
FsHttp.Fsi.enableDebugLogs()
```
--------------------------------
### Parse Response as JSON with System.Text.Json
Source: https://context7.com/fsprojects/fshttp/llms.txt
Handle JSON responses by parsing them into dynamic JsonElement objects for flexible access or into strongly-typed F# records. Supports custom deserialization options.
```fsharp
open FsHttp
// Raw JsonElement (dynamic access via ? operator)
let json =
get "https://reqres.in/api/users?page=2"
|> Request.send
|> Response.toJson
let page = json?page.GetInt32() // 2
let total = json?total.GetInt32() // 12
let firstName = json?data.[0]?first_name.GetString()
// Typed deserialization
type UserData = { id: int; email: string; first_name: string; last_name: string }
type UsersResponse = { page: int; data: UserData list }
let typed =
get "https://reqres.in/api/users?page=1"
|> Request.send
|> Response.deserializeJson
// Array of elements
let items =
get "https://reqres.in/api/users"
|> Request.send
|> Response.toJsonArray // JsonElement[]
// With custom options (e.g. FSharp.SystemTextJson)
open System.Text.Json
open System.Text.Json.Serialization
let opts =
let o = JsonSerializerOptions()
o.Converters.Add(JsonFSharpConverter())
o
type MaybeUser = { id: int; address: string option }
get "https://reqres.in/api/users/1"
|> Request.send
|> Response.deserializeJsonWith opts
```
--------------------------------
### Assert Response Status Codes
Source: https://context7.com/fsprojects/fshttp/llms.txt
Verify the HTTP status code of a response. `assert*` functions throw exceptions on failure, while `expect*` functions return a Result type for explicit error handling.
```fsharp
open FsHttp
let response =
http {
POST "https://reqres.in/api/users"
body
jsonSerialize {| name = "neo"; job = "the one" |}
}
|> Request.send
// Throws StatusCodeExpectedxception if not 201
response |> Response.assertStatusCode 201
// Returns Ok/Error Result
match response |> Response.expectStatusCode 201 with
| Ok r -> r |> Response.toJson |> fun j -> printfn "Created id: %s" (j?id.GetString())
| Error r -> printfn "Unexpected: %d" (int r.statusCode)
// Range helpers
response |> Response.assert2xx // 200–299
response |> Response.assertOk // exactly 200
response |> Response.assertNotFound // exactly 404
```
--------------------------------
### Read Response as Text or Bytes
Source: https://context7.com/fsprojects/fshttp/llms.txt
Extract the response body as a UTF-8 string, a truncated string, raw bytes, or a stream. Ensure proper disposal of streams.
```fsharp
open FsHttp
let response =
get "https://reqres.in/api/users"
|> Request.send
// Full text (UTF-8)
response |> Response.toText
// Truncated to N characters
response |> Response.toString (Some 500)
// Raw bytes
response |> Response.toBytes
// As stream
use stream = response |> Response.toStream
```
--------------------------------
### FsHttp Newtonsoft.Json Integration
Source: https://context7.com/fsprojects/fshttp/llms.txt
Integrate FsHttp with Newtonsoft.Json for deserializing JSON responses into strongly-typed F# records. Ensure the target type matches the JSON structure.
```fsharp
// Newtonsoft.Json integration
#r "nuget: FsHttp.NewtonsoftJson"
open FsHttp
open FsHttp.NewtonsoftJson
type User = { id: int; email: string }
get "https://reqres.in/api/users/1"
|> Request.send
|> Response.deserializeJson<{| data: User |}>
```
--------------------------------
### Send JSON String Request Body
Source: https://context7.com/fsprojects/fshttp/llms.txt
Send a raw JSON string with `Content-Type: application/json`. Supports literal strings, `sprintf`, and F# interpolated strings.
```fsharp
open FsHttp
// Literal JSON string
http {
POST "https://reqres.in/api/users"
body
json """{ "name": "morpheus", "job": "leader" }"""
}
|> Request.send
|> Response.toJson
|> fun j -> j?id.GetString()
```
```fsharp
// Parametrized with sprintf (no brace escaping needed)
let createUser name job =
http {
POST "https://reqres.in/api/users"
body
json (sprintf """{ \"name\": \"%s\", \"job\": \"%s\" }""" name job)
}
|> Request.send
```
```fsharp
// Parametrized with F# interpolated string (braces must be doubled)
let createUser2 name job =
http {
POST "https://reqres.in/api/users"
body
json $"""{{ "name": "{name}", "job": "{job}" }} """
}
|> Request.send
```
--------------------------------
### Send URL-Encoded Form Data
Source: https://context7.com/fsprojects/fshttp/llms.txt
Send form data encoded as `application/x-www-form-urlencoded` using the `formUrlEncoded` keyword.
```fsharp
open FsHttp
http {
POST "https://httpbin.org/post"
body
formUrlEncoded [
"username", "john"
"password", "s3cr3t"
"grant_type", "password"
]
}
|> Request.send
|> Response.toJson
|> fun j -> j?form?username.GetString()
// => "john"
```
--------------------------------
### Attach Cookies to Requests
Source: https://context7.com/fsprojects/fshttp/llms.txt
Cookies can be attached per-request at different scopes: simple name/value, scoped to a path, or scoped to a domain and path.
```fsharp
open FsHttp
http {
GET "https://httpbin.org/cookies"
// Simple name/value cookie
Cookie "session" "abc123"
// Cookie scoped to a path
CookieForPath "pref" "dark" "/settings"
// Cookie scoped to a domain and path
CookieForDomain "tracker" "xyz" "/" "example.com"
}
|> Request.send
|> Response.toText
```
--------------------------------
### Parse Response as XML
Source: https://context7.com/fsprojects/fshttp/llms.txt
Convert the response body to an XDocument for XML parsing. Access elements and attributes using LINQ to XML.
```fsharp
open FsHttp
get "https://httpbin.org/xml"
|> Request.send
|> Response.toXml // returns System.Xml.Linq.XDocument
|> fun doc -> doc.Root.Name.LocalName
// => "slideshow"
```
--------------------------------
### Access Dynamic JSON Properties with ? Operator
Source: https://context7.com/fsprojects/fshttp/llms.txt
Use the ? operator for dynamic access to properties within a JSON response. This requires the `JsonDynamic` module to be auto-opened.
```fsharp
// ? — dynamic JSON property access (from JsonDynamic, auto-opened)
let json = response |> Response.toJson
let total = json?total.GetInt32()
```
--------------------------------
### FsHttp FSharp.Data Integration
Source: https://context7.com/fsprojects/fshttp/llms.txt
Use this snippet to integrate FsHttp with FSharp.Data for JSON processing. It returns a FSharp.Data.JsonValue.
```fsharp
// FSharp.Data integration
#r "nuget: FsHttp.FSharpData"
open FsHttp
open FsHttp.FSharpData
get "https://reqres.in/api/users"
|> Request.send
|> Response.toJson // returns FSharp.Data.JsonValue
```
--------------------------------
### Convert Response to Result Type
Source: https://context7.com/fsprojects/fshttp/llms.txt
Transform a response into a `Result` type, where success (2xx status codes) contains the response, and failure (non-2xx) contains the error response. This allows for functional error handling.
```fsharp
open FsHttp
get "https://reqres.in/api/users/23"
|> Request.send
|> Response.toResult // Ok response (2xx) or Error response (non-2xx)
|> Result.map Response.toJson
|> Result.mapError (fun r -> int r.statusCode)
// => Error 404
```
--------------------------------
### Modify HttpClient Timeout
Source: https://context7.com/fsprojects/fshttp/llms.txt
Access and mutate the underlying .NET HttpClient to set configurations like a very short timeout. This is an escape hatch for low-level control.
```fsharp
// Modify the HttpClient (e.g. set a very short timeout)
http {
GET "https://reqres.in/api/users?delay=5"
config_transformHttpClient (fun client ->
client.Timeout <- System.TimeSpan.FromMilliseconds 500.0
client)
}
|> Request.send
```
--------------------------------
### Inspect and Mutate HttpRequestMessage
Source: https://context7.com/fsprojects/fshttp/llms.txt
Use `config_transformHttpRequestMessage` to inspect or mutate the outgoing `HttpRequestMessage` before it is sent. This allows for detailed logging or modification of request details.
```fsharp
// Inspect / mutate the HttpRequestMessage
http {
GET "https://reqres.in/api/users"
config_transformHttpRequestMessage (fun msg ->
printfn "Outgoing: %A %A" msg.Method msg.RequestUri
msg)
}
|> Request.send
```
--------------------------------
### Disable Automatic HTTP Redirects
Source: https://context7.com/fsprojects/fshttp/llms.txt
Configure the `HttpClientHandler` to disable automatic redirects. This provides control over how the client handles redirect responses.
```fsharp
// Set a custom HttpClientHandler (e.g. disable redirects)
http {
GET "https://reqres.in/api/users"
config_transformHttpClientHandler (fun handler ->
handler.AllowAutoRedirect <- false
handler)
}
|> Request.send
```
--------------------------------
### Disable FsHttp Debug Logs
Source: https://github.com/fsprojects/fshttp/blob/master/README.md
Call this function before making any requests to disable console logging in FsHttp.
```fsharp
FsHttp.Fsi.disableDebugLogs ()
```
--------------------------------
### Show Only Response Headers in FSI
Source: https://context7.com/fsprojects/fshttp/llms.txt
Limit FSI output to only display response headers, omitting the response body. This is useful for quickly checking status codes and metadata.
```fsharp
// Show only response headers
http {
GET "https://reqres.in/api/users"
print_headerOnly
}
```
--------------------------------
### Disable FSI Debug Logs Globally
Source: https://context7.com/fsprojects/fshttp/llms.txt
Turn off all FsHttp debug logging output in F# Interactive. This is useful for cleaning up the console output during development.
```fsharp
// Disable FSI debug logs globally
FsHttp.Fsi.disableDebugLogs()
```
--------------------------------
### Serialize F# Object to JSON Request Body
Source: https://context7.com/fsprojects/fshttp/llms.txt
Serialize an F# record or anonymous object to JSON using `System.Text.Json`. Supports custom `JsonSerializerOptions`.
```fsharp
open FsHttp
type CreateUserRequest = { name: string; job: string }
// Anonymous record
http {
POST "https://reqres.in/api/users"
body
jsonSerialize {| name = "morpheus"; job = "leader" |}
}
|> Request.send
```
```fsharp
// Named record
http {
POST "https://reqres.in/api/users"
body
jsonSerialize { name = "neo"; job = "the one" }
}
|> Request.send
```
```fsharp
// Custom JsonSerializerOptions (e.g. for FSharp.SystemTextJson)
open System.Text.Json
open System.Text.Json.Serialization
let opts =
let o = JsonSerializerOptions()
o.Converters.Add(JsonFSharpConverter())
o
http {
POST "https://reqres.in/api/users"
body
jsonSerializeWith opts { name = "trinity"; job = "operator" }
}
|> Request.send
```
--------------------------------
### Extract Raw HttpRequestMessage
Source: https://context7.com/fsprojects/fshttp/llms.txt
Obtain the raw `HttpRequestMessage` object without sending the request. This is useful for inspecting the constructed message or passing it to other .NET APIs.
```fsharp
// Extract the raw HttpRequestMessage without sending
let msg =
http { GET "https://reqres.in/api/users" }
|> Request.toHttpRequestMessage
```
--------------------------------
### Truncate Response Body in FSI Output
Source: https://context7.com/fsprojects/fshttp/llms.txt
Set a maximum length for the response body displayed in F# Interactive. This prevents overly large responses from cluttering the output.
```fsharp
// Truncate response body to 200 characters
http {
GET "https://reqres.in/api/users"
print_withResponseBodyLength 200
}
```
--------------------------------
### Disable HTTP Response Decompression
Source: https://context7.com/fsprojects/fshttp/llms.txt
Completely disable automatic decompression of HTTP responses. Use this when you need to handle the compressed content manually.
```fsharp
// Disable decompression entirely
get "https://reqres.in/api/users"
|> Config.noDecompression
|> Request.send
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.