In this article, I'll explain how to write a Facebook post using graph API from a C# console application.

To call the graph API, we need an access token. In this example, we will create a never expiring access token. Facebook offers short-lived access tokens (~2 hours), which can be used to generate a long live access token (~60 days).

https://developers.facebook.com/docs/facebook-login/access-tokens/refreshing

For this sample, generate a never-expiring access token. The generated token lifetime is based on the user that is creating it. From facebook docs:

if you use a Page administrator token and your app has business permissions, the returned Page access token does not expire.

Generate a never-expiring facebook access token

Head to https://developers.facebook.com/apps/ and Create an app. Give it the necessary information and click create

Create a facebook app

Create a user access token Go to https://developers.facebook.com/tools/explorer/. Make sure you have selected the app we created previously from the Application dropdown, then open the next dropdown and click 'Get User Access Token' option

Create a user token

That will open a modal window titled: 'Select Permissions'. manage_pages and publish_pages are minimal permissions you will need to publish a post in a page timeline.

Facebook permissions modal

Click get token. Follow the auth modal and make sure you select the page you intend to publish posts on.

Now from the previous steps, we have created a "Short-lived access token".

You can see all the tokens approved to your tasks in https://developers.facebook.com/tools/accesstoken/. To view more information about a token Click 'Debug' button next to it.

Debug facebook token

From this screen, you can see the lifetime of this token.

In the bottom of the screen, there is the option to extend the life of this token to 60 days. Click 'Extend Access Token', Authenticate and Submit.

Facebook: Extend access token life-span

Now a new long-lived token has been created. It will last for 60 days mine says "expires (in about 2 months)". This token can be used to generate a never-expiring one. Click the debug button next to it:

facebook long lived token

Now the last step: Copy the token generated in the previous step from the input box and head to: https://developers.facebook.com/tools/explorer/

  • Paste the token in "Access Token:" input box.
  • Update the graph query to be: 'me/accounts' and hit 'Submit'

Facebook api, never expiring token

Now check the JsonResponse. The field called "access_token" holds a never expiring token. To verify it paste it to https://developers.facebook.com/tools/debug/accesstoken and hit Debug. Here is mine:

Facebook api, never expiring token debug

C# HTTP call to create a Facebook post

From facebook docs https://developers.facebook.com/docs/graph-api/using-graph-api#publishing

To publish a post we need to make a HTTP call to https://graph.facebook.com/{your-page-id}/feed with two params:

  • message
  • access_token

Here's the cURL example:

curl -i -X POST \
  "https://graph.facebook.com/{your-page-id}/feed
    ?message=Awesome!
    &access_token={your-page-access-token}"

That, in C# can be accomplished with a FormUrlEncodedContent object post from a HttpClient. Here is the sample code:


    public class FacebookApi
    {
        private readonly string FB_PAGE_ID;
        private readonly string FB_ACCESS_TOKEN;
        private const string FB_BASE_ADDRESS = "https://graph.facebook.com/";

        public FacebookApi(string pageId, string accessToken)
        {
            FB_PAGE_ID = pageId;
            FB_ACCESS_TOKEN = accessToken;
        }

        public async Task<string> PublishMessage(string message)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(FB_BASE_ADDRESS);

                var parametters = new Dictionary<string, string>
                {
                    { "access_token", FB_ACCESS_TOKEN },
                    { "message", message }
                };
                var encodedContent = new FormUrlEncodedContent(parametters);

                var result = await httpClient.PostAsync($"{FB_PAGE_ID}/feed", encodedContent);
                var msg = result.EnsureSuccessStatusCode();
                return await msg.Content.ReadAsStringAsync();
            }

        }
    }