F# HTTP client
last modified December 4, 2026
In this article we send HTTP requests from F# with the .NET
HttpClient class.
HTTP is the protocol of the web. A client sends a request with a method
(GET, POST, and others), a URL, headers, and an
optional body; the server answers with a status code, headers, and a
body. HttpClient in System.Net.Http is part of
.NET. Its methods are asynchronous and return tasks, so we use the
task expressions from
F# async and tasks. JSON bodies are
read with System.Text.Json, covered in
F# JSON.
The examples use two free test services: httpbin.org, which echoes requests back, and jsonplaceholder.typicode.com, which serves fake users, posts, and to-do items. Neither stores the data we send.
A first request
GetStringAsync sends a GET request and returns
the response body as a string.
open System.Net.Http
let client = new HttpClient()
let body = client.GetStringAsync("https://jsonplaceholder.typicode.com/todos/1").Result
printfn "%s" body
HttpClient implements IDisposable, so it is
created with new. One client should be reused for many
requests: it keeps connections open, and creating a client per request
wastes sockets. Result waits for the task to finish; it is
fine at the top of a script, while the rest of the code stays in
task expressions.
λ dotnet fsi first.fsx
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Status codes
GetAsync returns the whole response as an
HttpResponseMessage. Its status code tells whether the
request succeeded.
open System.Net.Http
let client = new HttpClient()
let check (url: string) =
task {
let! response = client.GetAsync url
printfn "%d %A success: %b" (int response.StatusCode) response.StatusCode response.IsSuccessStatusCode
}
let run () =
task {
do! check "https://httpbin.org/status/200"
do! check "https://httpbin.org/status/404"
do! check "https://httpbin.org/status/503"
}
run().Wait()
StatusCode is an HttpStatusCode enum; cast to
int it gives the number. IsSuccessStatusCode is
true for codes 200 to 299. A response with an error code is still a
response: GetAsync does not throw for it.
λ dotnet fsi status.fsx 200 OK success: true 404 NotFound success: false 503 ServiceUnavailable success: false
Response headers and body
Headers describe the response. Those about the body, such as its type
and length, are in response.Content.Headers; the others are
in response.Headers.
open System.Net.Http
let client = new HttpClient()
let run () =
task {
let! response = client.GetAsync "https://jsonplaceholder.typicode.com/users/1"
let content = response.Content
printfn "content type: %O" content.Headers.ContentType
printfn "cache: %O" response.Headers.CacheControl
let! body = content.ReadAsStringAsync()
printfn "body has %d characters" body.Length
printfn "first line: %s" (body.Split('\n')[0])
}
run().Wait()
The headers have typed properties such as ContentType and
CacheControl; %O prints them with
ToString. ReadAsStringAsync reads the body.
λ dotnet fsi headers.fsx
content type: application/json; charset=utf-8
cache: max-age=43200
body has 509 characters
first line: {
Request headers
Headers set in DefaultRequestHeaders are sent with every
request of the client. The httpbin.org/user-agent address returns the
User-Agent header that it received.
open System.Net.Http
let client = new HttpClient()
let run () =
task {
let! before = client.GetStringAsync "https://httpbin.org/user-agent"
printfn "%s" before
client.DefaultRequestHeaders.UserAgent.ParseAdd "price-checker/1.2"
let! after = client.GetStringAsync "https://httpbin.org/user-agent"
printfn "%s" after
}
run().Wait()
By default HttpClient sends no User-Agent, so
the first answer has null. Some servers reject requests
without it. ParseAdd adds the header in the
product/version form.
λ dotnet fsi user_agent.fsx
{
"user-agent": null
}
{
"user-agent": "price-checker/1.2"
}
JSON responses
The System.Net.Http.Json namespace adds methods that combine
a request with JSON serialization. GetFromJsonAsync sends a
GET request and deserializes the body.
open System.Net.Http
open System.Net.Http.Json
type Address = { City: string; Zipcode: string }
type User = { Id: int; Name: string; Email: string; Address: Address }
let client = new HttpClient()
let run () =
task {
let! user = client.GetFromJsonAsync<User> "https://jsonplaceholder.typicode.com/users/3"
printfn "%d %s <%s>, %s" user.Id user.Name user.Email user.Address.City
let! users = client.GetFromJsonAsync<User list> "https://jsonplaceholder.typicode.com/users"
printfn "%d users" users.Length
}
run().Wait()
The JSON uses camel case ("name"), and the records use
Pascal case. GetFromJsonAsync uses the web defaults, which
match property names case-insensitively. The records need only the
fields we use; the other properties are ignored.
λ dotnet fsi users.fsx 3 Clementine Bauch <Nathan@yesenia.net>, McKenziehaven 10 users
Query strings
Parameters of a GET request go into the query string after
the ? in the URL. Values must be escaped, because characters
such as spaces and & have a special meaning in URLs.
open System
open System.Net.Http
open System.Net.Http.Json
open System.Text.Json.Nodes
let client = new HttpClient()
let queryString (pairs: (string * string) list) =
pairs
|> List.map (fun (k, v) -> $"{Uri.EscapeDataString k}={Uri.EscapeDataString v}")
|> String.concat "&"
let run () =
task {
let url = "https://httpbin.org/get?" + queryString [ "q", "tea & cake"; "page", "2" ]
printfn "%s" url
let! answer = client.GetFromJsonAsync<JsonNode> url
let args = answer["args"]
printfn "q = %s" (args["q"].GetValue<string>())
printfn "page = %s" (args["page"].GetValue<string>())
}
run().Wait()
Uri.EscapeDataString encodes the space as
%20 and the ampersand as %26. httpbin.org
returns the decoded parameters in args; it also returns our
headers and IP address, which we do not print. Reading into a
JsonNode lets us pick only the parts we need.
λ dotnet fsi query.fsx https://httpbin.org/get?q=tea%20%26%20cake&page=2 q = tea & cake page = 2
Sending JSON
PostAsJsonAsync serializes a value and sends it as the body
of a POST request. ReadFromJsonAsync
deserializes the body of the response.
open System.Net.Http
open System.Net.Http.Json
type NewPost = { UserId: int; Title: string; Body: string }
type Post = { Id: int; UserId: int; Title: string }
let client = new HttpClient()
let run () =
task {
let post = { UserId = 2; Title = "Spring cleaning"; Body = "Windows first." }
let! response = client.PostAsJsonAsync("https://jsonplaceholder.typicode.com/posts", post)
printfn "status: %d" (int response.StatusCode)
let! created = response.Content.ReadFromJsonAsync<Post>()
printfn "created post %d: %s" created.Id created.Title
}
run().Wait()
The record is sent in camel case with the
application/json content type. The service answers with
201 Created and the new post, including the id it assigned. The fake
service does not keep the post; it always assigns 101.
λ dotnet fsi post.fsx status: 201 created post 101: Spring cleaning
Updating and deleting
REST services use PUT to replace a resource and
DELETE to remove it. HttpClient has methods for
both.
open System.Net.Http
open System.Net.Http.Json
type Post = { Id: int; UserId: int; Title: string; Body: string }
let client = new HttpClient()
let url = "https://jsonplaceholder.typicode.com/posts/1"
let run () =
task {
let! original = client.GetFromJsonAsync<Post> url
let changed = { original with Title = "A better title" }
let! put = client.PutAsJsonAsync(url, changed)
let! updated = put.Content.ReadFromJsonAsync<Post>()
printfn "PUT %d: %s" (int put.StatusCode) updated.Title
let! delete = client.DeleteAsync url
printfn "DELETE %d" (int delete.StatusCode)
}
run().Wait()
We read the post, change its title with a copy and update expression,
and send the whole record back. DeleteAsync returns only a
response; a successful delete has status 200 or 204.
λ dotnet fsi put_delete.fsx PUT 200: A better title DELETE 200
Errors
Requests fail in two ways. The server may answer with an error status,
or there may be no answer at all, for example because the host does not
exist. EnsureSuccessStatusCode turns the first case into an
exception too, so both can be handled in one place.
open System.Net.Http
let client = new HttpClient()
let fetch (url: string) =
task {
try
let! response = client.GetAsync url
response.EnsureSuccessStatusCode() |> ignore
let! body = response.Content.ReadAsStringAsync()
return Ok body.Length
with :? HttpRequestException as e ->
return Error e.Message
}
let run () =
task {
for url in [ "https://httpbin.org/robots.txt"
"https://httpbin.org/status/500"
"https://no-such-host.invalid/" ] do
let! result = fetch url
match result with
| Ok n -> printfn "ok: %d characters" n
| Error msg -> printfn "error: %s" msg
}
run().Wait()
fetch returns a Result instead of letting the
exception escape. A try/with block inside a
task catches exceptions thrown while waiting with
let!. The .invalid top-level domain is reserved
and never resolves.
λ dotnet fsi errors.fsx ok: 30 characters error: Response status code does not indicate success: 500 (Internal Server Error). error: Name or service not known (no-such-host.invalid:443)
Timeouts
A slow server can keep a request waiting for a long time. The
Timeout property of the client limits it; the default is
100 seconds. httpbin.org/delay/N answers after N seconds.
open System
open System.Net.Http
open System.Threading.Tasks
let client = new HttpClient(Timeout = TimeSpan.FromSeconds 2.0)
let fetch (url: string) =
task {
try
let! _ = client.GetStringAsync url
return "ok"
with :? TaskCanceledException as e ->
return $"timeout: {e.Message}"
}
let run () =
task {
let! fast = fetch "https://httpbin.org/delay/1"
printfn "%s" fast
let! slow = fetch "https://httpbin.org/delay/4"
printfn "%s" slow
}
run().Wait()
When the time runs out, the request is canceled and the task throws
TaskCanceledException. The timeout applies to every request
of the client; set it before the first request.
λ dotnet fsi timeout.fsx ok timeout: The request was canceled due to the configured HttpClient.Timeout of 2 seconds elapsing.
Parallel requests
Requests that do not depend on each other can run at the same time.
Task.WhenAll waits for a list of tasks and returns their
results in the order of the list.
open System.Net.Http
open System.Net.Http.Json
open System.Threading.Tasks
type User = { Id: int; Name: string }
let client = new HttpClient()
let getUser (id: int) =
client.GetFromJsonAsync<User> $"https://jsonplaceholder.typicode.com/users/{id}"
let run () =
task {
let! users = Task.WhenAll [ for id in 1..5 -> getUser id ]
for u in users do
printfn "%d %s" u.Id u.Name
}
run().Wait()
The list comprehension starts five requests, because a task starts running when it is created. The program prints after all of them have finished, so the order of the output does not depend on which answer came first.
λ dotnet fsi parallel.fsx 1 Leanne Graham 2 Ervin Howell 3 Clementine Bauch 4 Patricia Lebsack 5 Chelsey Dietrich
Downloading a file
For larger bodies we read the response as a stream and copy it to a file, so that the whole file never sits in memory.
open System.IO
open System.Net.Http
let client = new HttpClient()
let download (url: string) (path: string) =
task {
use! stream = client.GetStreamAsync url
use file = File.Create path
do! stream.CopyToAsync file
}
let run () =
task {
do! download "https://httpbin.org/image/png" "pig.png"
let info = FileInfo "pig.png"
printfn "%s: %d bytes" info.Name info.Length
let! bytes = File.ReadAllBytesAsync "pig.png"
printfn "PNG signature: %b" (bytes[1..3] = "PNG"B)
}
run().Wait()
use! binds the stream and disposes it at the end of the
block, like use does for the file. We check the file by its
first bytes: a PNG image starts with byte 137 followed by the letters
PNG. "PNG"B is a byte array literal.
λ dotnet fsi download.fsx pig.png: 8090 bytes PNG signature: true
To-do report
The last program combines the pieces. It downloads users and to-do items in parallel and prints how many tasks each user has finished.
open System.Net.Http
open System.Net.Http.Json
open System.Threading.Tasks
type User = { Id: int; Name: string }
type Todo = { UserId: int; Title: string; Completed: bool }
let client = new HttpClient(BaseAddress = System.Uri "https://jsonplaceholder.typicode.com/")
let run () =
task {
let usersTask = client.GetFromJsonAsync<User list> "users"
let todosTask = client.GetFromJsonAsync<Todo list> "todos"
do! Task.WhenAll(usersTask, todosTask)
let users = usersTask.Result
let todos = todosTask.Result
let countByUser items =
items |> List.countBy (fun t -> t.UserId) |> Map.ofList
let total = countByUser todos
let finished = countByUser (todos |> List.filter (fun t -> t.Completed))
printfn "%-26s %s" "user" "done"
for u in users |> List.sortByDescending (fun u -> finished[u.Id]) do
printfn "%-26s %2d of %d" u.Name finished[u.Id] total[u.Id]
}
run().Wait()
BaseAddress lets the requests use relative URLs. Both
requests start before the first let!, and
Task.WhenAll waits for both; after it, reading
Result does not block. countByUser uses
List.countBy to count items per user id, once for all tasks
and once for the finished ones, and the users are sorted by the number
of finished tasks.
λ dotnet fsi report.fsx user done Chelsey Dietrich 12 of 20 Clementina DuBuque 12 of 20 Leanne Graham 11 of 20 Nicholas Runolfsdottir V 11 of 20 Kurtis Weissnat 9 of 20 Ervin Howell 8 of 20 Glenna Reichert 8 of 20 Clementine Bauch 7 of 20 Patricia Lebsack 6 of 20 Mrs. Dennis Schulist 6 of 20
Source
Make HTTP requests with the HttpClient class
HttpClientJsonExtensions class
In this article we have sent HTTP requests with HttpClient.
We have read bodies, status codes, and headers, set request headers,
read and sent JSON, built query strings, updated and deleted resources,
handled errors and timeouts, run requests in parallel, and downloaded a
file. Task expressions are covered in
F# async and tasks and JSON in
F# JSON.
Author
List all F# tutorials.