Tuesday, April 7, 2020

Learning F# - Step 6

The next step in my learning journey for a new language is to figure out how to access web APIs.

When I searched for how to access web APIs, I was brought back to FSharp.Data. This library also provides interfaces to make HTTP calls! (I was a little leery about using this package after my experience with the data access!)

As it turns out, this library works really well for HTTP calls! Once I added it my project with the call:

dotnet add package FSharp.Data
and referenced the package in my code with:
open FSharp.Data
I was able to start accessing web sites.

Below is the most basic web request that you can make. In my case, I just pulled up Google and printed the HTML response to the console:

let google = Http.RequestString("http://www.google.com")
printfn "%s" google
This code calls "www.google.com" and prints the result to the console. This is a great start, but I need to be able to do more.

The next step for me is to figure out how to do more complex calls. That was fairly easy too. The following code calls Google with a specific search term and prints the result to the console:

let searchResults = Http.RequestString("http://www.google.com/search",
                                       httpMethod = "GET",
                                       query = [ "q", "butterflies"])
printfn "%s" searchResults
This code illustrates a few things that we need to know to access web APIs. First, it gives us a way to specify the HTTP verb: httpMethod = "GET". It also shows us how to send query parameters using query. The query parameter takes an array of items. If we needed to emulate a form submission, we can change the HTTP verb to POST and send in a body element with an array of values, just like the query parameter.

Now that I have learned some basic tasks to accomplish in F#, I can start using it to solve some real-world problems to learn the actual language. In my next post, I'll talk about some odds-and-ends I've found along this journey, as well as some good sites for diving into F# and getting a handle on functional programming.

No comments:

Post a Comment