Jomo Fisher – The web service at Freebase.com lets you access all sorts of structured data from a web service. Here’s a sample that shows you how to access this data from F#. It uses DataContract and the JSON serializer. The code below reads and prints the elements of the periodic table.

Code Snippet
  1. // Freebase.fsx
  2. // Example of reading from freebase.com in F# using DataContract and JSON serializer
  3. // by Jomo Fisher
  4. #r "System.Runtime.Serialization"
  5. #r "System.ServiceModel.Web"
  6. #r "System.Web"
  7. #r "System.Xml"
  8.  
  9. open System
  10. open System.IO
  11. open System.Net
  12. open System.Text
  13. open System.Web
  14. open System.Security.Authentication
  15. open System.Runtime.Serialization
  16.  
  17. [<DataContract>]
  18. type Result<'TResult> = {
  19.     [<field: DataMember(Name="code") >]
  20.     Code:string
  21.     [<field: DataMember(Name="result") >]
  22.     Result:'TResult
  23.     [<field: DataMember(Name="message") >]
  24.     Message:string
  25.     }
  26.  
  27. [<DataContract>]
  28. type ChemicalElement = {
  29.     [<field: DataMember(Name="name") >]
  30.     Name:string
  31.     [<field: DataMember(Name="boiling_point") >]
  32.     BoilingPoint:string
  33.     [<field: DataMember(Name="atomic_mass") >]
  34.     AtomicMass:string
  35.     }
  36.  
  37. let Query<'T>(query:string) : 'T =
  38.     let query = query.Replace("'","\"")
  39.     let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}"
  40.  
  41.     let request : HttpWebRequest = downcast WebRequest.Create(queryUrl)
  42.     request.Method <- "GET"
  43.     request.ContentType <- "application/x-www-form-urlencoded"
  44.  
  45.     let response = request.GetResponse()
  46.  
  47.     let result =
  48.         try
  49.             use reader = new StreamReader(response.GetResponseStream())
  50.             reader.ReadToEnd();
  51.         finally
  52.             response.Close()
  53.  
  54.     let data = Encoding.Unicode.GetBytes(result);
  55.     let stream = new MemoryStream()
  56.     stream.Write(data, 0, data.Length);
  57.     stream.Position <- 0L
  58.     
  59.     let ser = Json.DataContractJsonSerializer(typeof<Result<'T>>)
  60.     let result = ser.ReadObject(stream) :?> Result<'T>
  61.     if result.Code<>"/api/status/ok" then
  62.         raise (InvalidOperationException(result.Message))
  63.     else
  64.         result.Result
  65.  
  66. let elements = Query<ChemicalElement array>("[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]")
  67.  
  68. elements |> Array.iter(fun element->printfn "%A" element)

Let me know if there are other F# samples you’d like to see.

This posting is provided "AS IS" with no warranties, and confers no rights.