Download leads from the Facebook API

Introduction

Consider the scenario where Contoso Water Purifiers have a Facebook page to advertise their products and generate leads. A potential customer views this page and is interested in a particular product, so they enter their contact details in the leads form. In order for the business to easily view such leads, they ask their IT department to write an app which downloads customer leads from Facebook using the Facebook REST API. (Although not discussed in this post, it’s expected that these leads would then be entered in the business’ internal IT systems.)

The following section demonstrates how a developer from the IT department goes about implementing this business requirement. That is, the steps they take to write a C# console app (.NET Framework) to connect to the Facebook REST API and download leads.

Create the C# console app which connects to the Facebook REST API

1.) Retrieve the leads form Id from within the business’ Facebook page (Figure 1)

Figure 1

2.) Register to use developers.facebook.com/apps/ and create a Facebook app by selecting ‘Manage Business Integrations’.

3.) Use the Facebook Graph API explorer to generate an access token and use this token to validate that the Facebook REST API is working as expected (Figure 2).

Figure 2

4.) Take the Facebook REST API JSON response and paste it into Visual Studio by selecting ‘Paste Special’, ‘Paste JSON As Classes’. This generates the schema ‘model’ shown in Figure 3. The Facebook JSON response deserialisation is based on this schema (Figure 4)

Figure 3

5.) Write the C# code displayed in Figure 4

Figure 4

6.) Run the C# console app. Referring to Figure 4

  • The HttpClient GetAsync() call (line 2) executes and makes an asynchronous call to the Facebook REST API. This is a non blocking call and will suspend the function RetrieveLeadsfromFacebookForm() and return immediately to the caller (line 1).
  • The async call returns, and line 3 executes. This deseralises the Facebook REST API JSON response into an object called FacebookLeads
  • The FacebookLeads object on line 1 is populated (Figure 5).
Figure 5

7.) View the values extracted from the JSON response in Figure 6

Referring to line 146 in Figure 6, the first ‘x’ represents a list of name/value pairs. The value returned is the value associated to the name ‘first_name’.

Figure 6

Further Reading

Download leads from the Facebook API issue

References

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators

c#6 – Null-Conditional Operator