Developer's Guide: .NET

Important: This is an old version of this page. For the latest version, use the links in the left-side navbar.

The Blogger Data API allows client applications to view and update Blogger content in the form of Google Data API feeds.

Your client application can use the Blogger Data API to create new blog posts, edit or delete existing blog posts, and query for blog posts that match particular criteria.

In addition to providing some background on the capabilities of the Blogger Data API, this document provides examples of basic Data API interactions using the .NET client library. If you're interested in understanding more about the underlying protocol that the library uses, see the Protocol section of this developer's guide.

Contents

Audience

This document is intended for programmers who want to write .NET client applications that can interact with Blogger.

This document assumes that you understand the general ideas behind the Google Data APIs protocol.

For reference information about the classes and methods provided by the client library, see the .NET client library API reference. For general Blogger Data API reference information, see the Protocol reference guide.

Getting started

For help setting up the client library, see the Getting Started Guide.

To use the .NET client library, you'll need the .NET 1.1 runtime, and you should also be current on all patches. After downloading the client library, you'll find the DLLs you need to get started in the lib/Release subdirectory of the distribution.

Creating a Blogger account

You may want to sign up for a Blogger account for testing purposes. Blogger uses Google Accounts, so if you already have a Google account, you're all set.

Running the sample code

A full working sample client, containing all the sample code shown in this document, is available in the .NET client library project. The sample is located at /trunk/clients/cs/samples/blogger/ConsoleSample.cs in the Source tab of the SVN repository.

Before compiling and running this sample, update the values of username, password, blogName, and postId with the appropriate values. The username and password values represent the credentials used to log in to Blogger. The blogName value is the start of your blog's blogspot URL.

The sample client performs several operations on the provided blog to demonstrate the use of the Blogger Data API.

To compile the examples in this document into your own code, you'll need the following using statements:

using Google.GData.Client;
using System.Net;
using System.Xml;
using System.Text.RegularExpressions;

Authenticating to the Blogger service

You can access both public and private feeds using the Blogger Data API. Public feeds don't require any authentication, but they are read-only. If you want to modify blogs, then your client needs to authenticate before requesting private feeds. It can authenticate using either of two approaches: AuthSub proxy authentication or ClientLogin username/password authentication.

For more information about authentication with Google Data APIs in general, see the authentication documentation.

AuthSub proxy authentication

AuthSub proxy authentication is used by web applications that need to authenticate their users to Google Accounts. The website operator and the client code don't have access to the username and password for the Blogger user; instead, the client obtains special AuthSub tokens that allow the client to act on a particular user's behalf. For more detailed information, see the AuthSub documentation.

When a user first visits your application, they have not yet been authenticated. In this case, you need to display some information and a link directing the user to a Google page to authenticate your request for access to their blogs.

Suppose the following ASP hyperlink is defined in your page:

<asp:HyperLink ID="GotoAuthSubLink" runat="server"/>

Then to construct the AuthSubRequest URL for your application, make a .NET client library call as follows:

GotoAuthSubLink.Text = "Login to your Google Account";
GotoAuthSubLink.NavigateUrl =
  AuthSubUtil.getRequestUrl("http://www.example.com/RetrieveToken",
  "http://www.blogger.com/feeds/",
  false,
  true);

The getRequestUrl method takes the following parameters (corresponding to the query parameters used by the AuthSubRequest handler):

next
The URL of the page that Google should redirect the user to after authentication.
scope
Indicates that the application is requesting a token to access Blogger feeds. The scope string to use is http://www.blogger.com/feeds/ (URL-encoded, of course).
secure
Indicates whether the client is requesting a secure token.
session
Indicates whether the token returned can be exchanged for a multi-use (session) token.

The above example shows a call that doesn't request a secure token (the value of secure is false). The resulting request URL might look like this:

https://www.google.com/accounts/AuthSubRequest?scope=http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F&session=1&secure=0&next=http%3A%2F%2Fwww.example.com%2FRetrieveToken

The user follows the link to Google's site and authenticates to their Google Account.

After the user authenticates, the AuthSub system redirects them to the URL you specified in the next query parameter of the AuthSubRequest URL. The AuthSub system appends an authentication token to that URL, as the value of the token query parameter. Therefore, the token is accessible as a variable in the ASP page's Request.QueryString object. The user is redirected to a URL that looks like this:

http://www.example.com/RetrieveToken?token=yourAuthToken

This token value represents a single-use AuthSub token. In this example, since session = true was specified, this token can be exchanged for an AuthSub session token, as follows:

SessionsessionToken = AuthSubUtil.exchangeForSessionToken(Request.QueryStringtoken, null);

That is, you pass your one-time-use token to the exchangeForSessionToken method, along with either null (for unregistered mode) or a private key (for registered mode), and the AuthSub interface returns a session token. For more information about registered applications and private keys, see the "Signing requests" section of the AuthSub documentation.

Your application can then use the session token value in subsequent interactions with Blogger. To tell the .NET client library to automatically send the Authorization header (containing the session token) with each request, do the following:

GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("blogger", "BloggerSampleApp");
authFactory.Token = SessionsessionToken.ToString();
Service service = new Service(authFactory.ApplicationName);
service.RequestFactory = authFactory;

ClientLogin username/password authentication

Use ClientLogin authentication if your client is a standalone, single-user "installed" client (such as a desktop application). Set the credentials of your service object as follows:

Service service = new Service("blogger", "exampleCo-exampleApp-1");
service.Credentials = new GDataCredentials("user@example.com", "secretPassword");
GDataGAuthRequestFactory factory = (GDataGAuthRequestFactory) service.RequestFactory;
factory.AccountType = "GOOGLE";

In the snippet above, we pass two parameters to the Service constructor. The first parameter is the name of the service we want to interact with. The second parameter is the name of our application in the form companyName-applicationName-versionID. We also set the Service.RequestFactory to only use a GOOGLE account type in order to allow proper authentication for G Suite users.

For more information about ClientLogin authentication, including sample requests and responses, see the Authentication for Installed Applications documentation.

Note: Use the same token for all requests in a given session; don't acquire a new token for each Blogger request.

Note: As described in the ClientLogin documentation, the authentication request may fail and request a CAPTCHA challenge. If you want Google to issue and handle the CAPTCHA challenge, then send the user to https://www.google.com/accounts/DisplayUnlockCaptcha?service=blogger (rather than to the CAPTCHA-handling URL given in the ClientLogin documentation).

Retrieving a list of blogs

The Blogger Data API provides a feed that lists the blogs for a particular user; that feed is known as a "metafeed."

The following sample code uses an authenticated Service object to retrieve the metafeed and then prints each blog's title.

query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs");
AtomFeed feed = null;
try
{
  feed = service.Query(query);
  foreach (AtomEntry entry in feed.Entries)
  {
    Console.WriteLine("Blog Title: " + entry.Title.Text);
  }
}

Note the URL used by the getFeed method. This is the default metafeed URL; it returns a list of blogs for the currently authenticated user. To access a feed for a different user, you can put the user's ID in place of default in the metafeed URL. The user's ID is the string of digits at the end of the user's profile URL.

Creating posts

The Blogger Data API allows you to create and publish new blog entries, as well as creating drafts of entries.

All of the following samples assume you have an authenticated Service object.

Note: Setting a custom author for posts is currently not supported. All new posts will appear as if they were created by the currently authenticated user.

Publishing a blog post

You can use the .NET client library to publish new blog entries.

First, create an AtomEntry object to represent the blog post. Then you can set the title, content and other attributes of the blog post. Finally, use the Service object to insert the post. Here's an example of how to publish a new blog post:

AtomEntry newPost = new AtomEntry();
newPost.Title.Text = "Marriage!";
newPost.Content = new AtomContent();
newPost.Content.Content = "<div xmlns='http://www.w3.org/1999/xhtml'>" +
  "<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" +
  "<p>He is the last man on earth I would ever desire to marry.</p>" +
  "<p>Whatever shall I do?</p>" +
  "</div>";
newPost.Content.Type = "xhtml";

Uri blogFeedUri = new Uri("http://www.blogger.com/feeds/" + blogId + "/posts/default");
AtomEntry createdEntry = service.Insert(blogFeedUri, newPost);

The Insert method takes the service's post URL as a parameter. Then the method returns the entry as it was stored by Blogger. The entry returned is the same one you sent, but it also contains various elements added by Blogger, such as a post ID.

If your request fails for some reason, Blogger may return a different status code. For information about the status codes, see the Google Data API protocol reference document.

Creating a draft blog post

Draft posts are created in the same way as public posts, but you need to set the draft attribute of the AtomEntry object. The blog post above could be created as a draft by adding the highlighted line:

AtomEntry newPost = new AtomEntry();
newPost.Title.Text = "Marriage!";
newPost.Content = new AtomContent();
newPost.Content.Content = "<div xmlns='http://www.w3.org/1999/xhtml'>" +
    "<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" +
    "<p>He is the last man on earth I would ever desire to marry.</p>" +
    "<p>Whatever shall I do?</p>" +
    "</div>";
newPost.Content.Type = "xhtml";
newPost.IsDraft = true;

Uri blogFeedUri = new Uri("http://www.blogger.com/feeds/" + blogId + "/posts/default");
AtomEntry createdEntry = service.Insert(blogFeedUri, newPost);

You can turn an existing draft blog post into a published post by retrieving the draft post, setting the draft attribute to false, and then updating the post. We'll cover retrieving and updating posts in the next two sections.

Retrieving posts

The following sections describe how to retrieve a list of blog posts, with and without query parameters.

You can query a Blogger public feed without authentication. Therefore, you don't need to set credentials or do AuthSub authentication before retrieving posts from a public blog.

Retrieving all blog posts

To retrieve the user's posts, call the same getFeed method used to retrieve the blogs metafeed, but this time send the blog-post feed URL:

query.Uri = new Uri("http://www.blogger.com/feeds/" + blogId + "/posts/default");
feed = service.Query(query);
Console.WriteLine(feed.Title.Text);
foreach (AtomEntry entry in feed.Entries)
{
  Console.WriteLine("Entry Title: " + entry.Title.Text);
}

Retrieving posts using query parameters

The Blogger Data API lets you request a set of entries that match specified criteria, such as requesting blog posts published or updated in a given date range. To do this, you create a FeedQuery object and pass it to the Service.Query() method.

For example, to send a date-range query, set the MinPublication and MaxPublication members of the FeedQuery object. The following code snippet prints the title of each blog post published between the given start time and end time:

FeedQuery query = new FeedQuery();
query.Uri = new Uri("http://www.blogger.com/feeds/" + blogId + "/posts/default");
query.MinPublication = new DateTime(2006, 1, 1);
query.MaxPublication = new DateTime(2007, 4, 12);
AtomFeed feed = service.Query(query);
foreach (AtomEntry entry in feed.Entries)
{
  Console.WriteLine("  Entry Title: " + entry.Title.Text);
}

Notice that the FeedQuery object is constructed using the same post feed URL used to retrieve posts.

The Blogger Data API supports the following query parameters:

alt
The type of feed to return, such as atom (the default) or rss.
/category
Specify categories (also known as labels) to filter the feed results. For example, http://www.blogger.com/feeds/blogID/posts/default/-/Fritz/Laurie returns entries with both the labels Fritz and Laurie.
max-results
The maximum number of entries to return.
orderby
The order in which to return entries, such as lastmodified (the default), starttime, or updated.
published-min, published-max
The bounds on entry publication dates.
start-index
The 1-based index of the first result to be retrieved (for paging).
updated-min, updated-max
The bounds on entry update dates. These query parameters are ignored unless the orderby parameter is set to updated.

For more information about query parameters, see the Blogger Data API Reference Guide and the Google Data APIs Reference Guide.

Updating posts

To update an existing blog post, first you retrieve the entry you want to update, then you modify it, and then you send it to Blogger using the entry's Update() method. The following code snippet modifies the title of a blog entry, assuming that you've already retrieved the entry from the server.

static AtomEntry EditEntry(AtomEntry toEdit)
{
  // Edit the entry by changing the Title and calling Update().
  if (toEdit != null)
  {
    toEdit.Title.Text = "Marriage Woes!";
    toEdit = toEdit.Update();
  }
  return toEdit;
}

The above code returns an AtomEntry containing the entire newly-updated post. To update any other properties, simply set them in the AtomEntry object before calling Update().

Note: Modifying the author data associated with posts is currently not supported.

Deleting posts

To delete a post, call the Delete method on an existing AtomEntry object, like this:

static void DeleteEntry(AtomEntry toDelete)
{
  // Delete the edited entry
  if (toDelete != null)
  {
    toDelete.Delete();
  }
}

Comments

The Blogger Data API allows for creating, retrieving, and deleting comments. Updating comments is not supported (nor is it available in the web interface).

Creating comments

To post a comment, create an AtomEntry object and insert it as follows:

AtomEntry comment;
comment = new AtomEntry();
comment.Title.Text = "This is my first comment";
comment.Content.Content = "This is my first comment";
Uri commentPostUri = new Uri("http://www.blogger.com/feeds/" + blogId + "/" + entryId + "/comments/default");
postedComment = service.Insert(commentPostUri, comment);

Note: Currently, you can only post comments to a blog owned by the authenticated user.

Note: Setting a custom author for comments is currently not supported. All new comments will appear as if they were created by the currently authenticated user.

Retrieving comments

You can retrieve the comments for a particular post from the post's comments feed URL:

static void ListEntryComments(Service service, Uri commentUri)
{
  if (commentUri != null)
  {
    // Retrieve all comments on a blog entry
    FeedQuery query = new FeedQuery();
    query.Uri = commentUri;
    AtomFeed feed = service.Query(query);
    foreach (AtomEntry entry in feed.Entries)
    {
      Console.WriteLine("  Comment Title: " + entry.Title.Text);
    }
  }
}

Or you can get the comments from all posts by using the blog's comments feed URL:

http://www.blogger.com/feeds/blogID/comments/default

Deleting comments

To delete a comment, call the Delete() method on an existing comment AtomEntry object like this:

static void DeleteComment(AtomEntry commentEntry)
{
  if (commentEntry != null)
  {
    // Delete the comment.
    commentEntry.Delete();
  }
}

Back to top