If you're new to the Twitter API and would like to learn more about it, this excerpt from Kevin Makice's Twitter API: Up and Running will get you up to speed.
kmakice The ingredients for your Twitter application are found in the methods of the API. This chapter is your shopping cart.
Now that you know what Twitter is all about (Chapter 1, Hello Twitter) and have the basic skills to play in the sandbox (Chapter 3, Web Programming Basics), it’s time to introduce you to the building blocks for your future application. This chapter describes the specific request methods available through the Twitter API.
The section of the Twitter website that talks about the API groups the methods based on their server paths. This may be a bit confusing, for a few reasons. Some of the terminology is old and doesn’t fit with the way we talk about the service today. It is also very techie language, with words like “destroy” instead of “remove” or even “delete.” To help you get started, in this chapter I’ll drop the tech talk and reorganize the methods into groups reflecting how you might actually use them.
In each section, I’ll present one of the 40 existing API methods and explain what is needed to get data from Twitter using that method. Before we start talking about parameters and data formats, though, you need to understand how to connect to the API.
Note
Chapters 6 through 8 provide a description of a suite of web
applications used to illustrate how everything goes together. However,
sometimes the best way to understand how something works is to play with
the input and output. To help with this, the sample code for this book
includes a /test directory containing web forms that
interface with the Twitter API. You can use these test pages to see the
XML that is returned by Twitter. The sample code can be downloaded from
http://www.oreilly.c.../9780596154615/.
An application programming interface, or API, is what allows an application with data to share it with the rest of the world. An API is like a no-frills website, accessed through URL requests but returning structured data instead of web pages displayed in a browser. The data returned is structured to make it easy to parse and get to the information inside. APIs also tend to separate all of the functionality of the site into single, specific actions, such as “get a list of tweets” or “change my profile picture.” By combining several kinds of requests, you can use an API to power your own custom applications.
The design of the Twitter API attempts to adhere to the principles of RESTful systems. Roy Fielding conceived of REpresentational State Transfer (REST) less than a decade ago: this approach increases the ease of development as well as the scalability and flexibility of applications by making sure the data is layered, stateless, and well defined. Switching from XML to JSON, for example, is a simple matter of changing the extension on the URL used to make the request; it isn’t necessary to reengineer the application or switch development platforms.
In this section, I’ll present you with some basic instructions on how to access the Twitter API, select from HTTP methods, authenticate your API requests, and manage imposed limits.
The Twitter API permits three kinds of HTTP requests: GET, POST, and DELETE. The default request is submitted with a GET, which passes parameters as an encoded URL query string. For API methods that change things—for example, updating or deleting status information, direct messages, or associations in the follow network—a POST is needed.
Note
Where indicated in the API methods, the id parameter is sent as part of the URL (substitute this parameter
with either a user ID or a username). No form data is needed for any
of these methods.
The GET method accepts a URL and uses it to retrieve something from another server, after any necessary processing is done. If the URL is an index.php web page, for example, the GET method will capture the HTML generated by the PHP, not the PHP code itself.
Header information passed to the GET method can change its
behavior. In particular, GET looks at the If-Modified-Since field and captures the
output only if doing so fulfills that header
condition. The purpose of this constraint is to reduce redundant
network activity by avoiding unnecessary data transfers.
The following Twitter API methods are accessed with a GET:
Note
Most of the methods in the API can be requested using GET.
This means your parameters can be passed as a URL query string, or a
series of name/value pairs following a ?.
This is great for testing, as all you need to do is type the request URL into the location bar in a regular browser. If the method requires authentication, a dialog box will pop up to get that information. This is more convenient than running early source code or using cURL, as described later in this chapter.
The POST method does the same thing as GET, but it acquires its results in a different way. Whereas there is an upper limit on the size of a GET query string, a POST request encapsulates the submitted data, allowing more information to be transferred. It treats that bundle of data like an attachment to an email, something separate from and subordinate to the requested URL rather than part of it. Because the data is encapsulated and sent separately from the URL, POST data is not exposed in server logs.
Warning
POST data should not be treated as implicitly secure. It does help guard against simple attacks such as image-based cross-site request forgeries (see http://en.wikipedia.org/wiki/CSRF for more details), but it is only “security by obscurity.”
POST is required for API methods that actually make changes to Twitter’s servers, rather than just retrieving data. This is typical of all APIs and web forms in general, and is not unique to Twitter. In the Twitter API, the following methods require POST request handling:
https://twitter.com/...uses/update.xmlNote
POST requests to the API do not count against the rate limit.
The Twitter API also accommodates a third protocol, the DELETE method. The purpose of this type of HTTP call is to instruct the remote server to remove the requested URL resource. There is no way for the remote client to guarantee that this has been done, however. POST requests work just as well with the API, and in this book we’ll use POST instead of DELETE.
There are only a handful of API methods that will recognize a DELETE request:
One of the bits of information returned to the client in an HTTP request is the status code, a series of three-digit numbers used to communicate the type of success or failure encountered. The Twitter API assigns special meanings to many of these codes, which describe specific outcomes of method requests.
The following are some status codes your application may encounter, and what they likely mean in the context of the API:
- 200—OK
Success! The method request did what you expected it to do.
- 304—Not Modified
Nothing wrong, but nothing to report.
- 400—Bad Request
This can be caused by one of two things: either the request was formatted incorrectly (missing required parameters, unknown method, etc.), or the rate limit has been exceeded. Check the returned text for an explanation.
- 401—Not Authorized
The account (Twitter username or registered email address) or password you used to authenticate to the API isn’t working. Check its accuracy and try again.
- 403—Forbidden
Twitter understood what you want to do, but won’t let you do it. Check the returned text for an explanation.
- 404—Not Found
Probably caused by a typo or incorrect path to the API method you are requesting. You might also get this error when trying to request a nonexistent user.
- 500—Internal Server Error
The Twitter folks may be working under the hood. What you requested is probably OK, but the servers aren’t handling it correctly. Seek counsel from engineers on the Twitter Development Talk Google Group.
- 502—Bad Gateway
Intentional Fail Whale; Twitter is probably rolling out an upgrade.
- 503—Service Unavailable
Unintentional Fail Whale (see the section called “The Rise of the Fail Whale”); there are too many requests for the servers to handle right now.
Twitter will try to return any error messages in the same format being requested for the data, such as this XML version:
Authentication required to request your own timeline. /statuses/user_timeline.xml
The default format is text. Twitter will always try to return some kind of explanation, if it can.
Status codes are an easy way to direct the application logic. Parsing the returned messages will provide specifics and can be helpful for passing along interpretations of errors to the end user, but status codes are easier to access from the HTTP response. They can help direct error handling or confirm success.
Twitter currently accommodates four kinds of formatted data:
- XML
Extensible Markup Language uses semantic tags to wrap data in a structured format. It is extensible because the user can define the structure and kinds of tags; they aren’t simply prescribed, as with HTML. Use of XML to structure data is an accepted way to separate the data layer from the presentation layer and make applications more versatile.
- JSON
Javascript Object Notation is a language-independent text format used primarily to power Ajax applications. With JSON, simple text can be used to represent many different types of data and the relationships between those data types. As with XML, the data is encapsulated in a structured format; however, JSON is considered to be simpler than XML. For more information on how to use JSON, visit http://www.json.org.
- RSS
Really Simple Syndication is a specific form of XML that reflects some standardized tag structures that can be read in a predictable manner. RSS feeds are widespread on blogs, news websites, and services like Twitter.
- Atom
Atom Syndication Format is an alternative to RSS that was created in part to remove the need for legacy support of older protocols. Atom uses a different date and time format than RSS and is more accommodating of modular use and international support.
We’ll use XML in this book, but to switch to JSON, simply change
the URL extension from .xml to
.json in the HTTP request. That’s
what RESTful design principles do for you!
Only a few Twitter API methods make use of the RSS and Atom formats. The following are used on the official Twitter website, allowing people to subscribe to information streams:
Most API requests require a valid username and password. Authentication is necessary for two reasons. First, some of the information available through the API is specific to the authenticated user, so the user context determines what data is returned. Second, authentication is the most reliable way to facilitate limiting the rate of access to the API. Imposing rate limits was necessary to ensure the success of Twitter, in terms of both cultivating members and encouraging third-party application development.
Note
Asking for authentication information from users is difficult to avoid for some of the functions and data available through the Twitter API. For further discussion on some of the issues involved with asking end users to provide their username and passwords, see the section called “Gone Phishing: A Word About Passwords”.
Although Twitter does have plans to improve the scheme to use OAuth,[62] as of this writing authentication is done through HTTP Basic Authentication, referred to as Basic Auth. Twitter asks for either an account username or the email address used to create the account, along with a password, before doing any of the heavy lifting in terms of data retrieval or modification. Any future changes are likely to become optional improvements, with the current system remaining fully supported.
Warning
Be aware that the user account information passed as plain text in cURL is only slightly obfuscated; it will be fully readable to anyone monitoring the network. cURL facilitates HTTPS requests, and Twitter recommends using encryption to interact with the API.
If a method is requested without a valid username and password, the data response will be XML containing the following error statement:
Could not authenticate you. /account/verify_credentials.xml
If you are not interested in the specifics of the error message (which can easily change), examine the HTTP status code as a quicker and more reliable indication of success or failure (see the section called “HTTP Status Codes”).
There are a few API methods that return data without authentication. Here’s the complete list:
- View the Public Timeline
- View an Individual Timeline (public accounts only)
- Show a Tweet
- Show Member Profile
- Keyword Search
- Test
All of these unauthenticated methods require a GET request, and some (such as Member Profile) will provide more information if the user context is known when the information is retrieved.
Note
At press time, Twitter’s OAuth was in beta, being tested by the developer community. One of the testers, Abraham Williams, quickly published some sample code at http://github.com/po...ch/twitteroauth. See the next section for more on OAuth.
In February 2009, Twitter released its first implementation of OAuth as a closed beta to developers on the Google discussion group. A few hours after this release, Inuda, a web application design firm, quickly showed a proof of concept with Twitter’s code.[63] Within a week, successful tests and sample code existed for PHP, Python, and Ruby. A growing list of OAuth resources is available on the Twitter API wiki.
Among those efforts was a sample script from Abraham Williams (@poseurtech).[64] Williams’ solution follows a straightforward process to authenticate with Twitter’s OAuth. OAuth functions by managing multiple pairs of tokens: the tokens for the specific user request, and the ones used to allow the application to later access parts of that user’s Twitter account. There is also an initial pair used to register the application.
Each application will first need to be registered with Twitter.
Developers in the beta test were given a new tab in the Settings section
of the Twitter website that allowed them to make this request. Twitter
returns the key/secret tokens for the application to build a
TwitterOAuth object from the registered URI. With the
key and secret strings, the application requests tokens for the user
with a new OAuth method. These tokens become part of a request link that
the end user can click on to grant the application access to her Twitter
account.
In Basic Auth, Twitter isn’t involved with this handoff of account access. Users share their screen names and passwords with the third-party application, which then uses them to access the API on their behalf. Not only is this an all-or-nothing level of access, but it is the same access that would be shared with other third-party applications. The result is a network of systems reliant on the same authentication information.
With OAuth, Twitter becomes the middleman in the negotiation between the application and the user. The application uses its identifying tokens—acquired through the initial registration—to request access to the user’s account in the form of a request link. This link is presented to the user on the third-party application, sort of like how a parking receipt is given to a conference attendee to take to the information desk to be validated. When the user clicks on this link, he is taken to the Twitter website, along with the tokens that identify which application will need the account access. At this point, the application is no longer involved; it is a dialogue between the user and Twitter. If the former approves access, he is taken back to the third-party application site with the token pair needed to make future API requests.
This only gets us halfway there. These request tokens are saved locally by the third-party application and used whenever more API interaction is required. The request tokens don’t grant access, but they do authorize future requests for data without the user being present. Assuming the user hasn’t revoked access in the interim, the application can present the request tokens to get access to the user’s data—sort of like giving a special pass to a bouncer to get backstage at a concert.
The big benefit of OAuth is that it avoids password-sharing behavior. Instead of asking the user to provide her actual username and password, the OAuth process results in a new form of the user authentication that can only be used by this particular application. For third-party applications, there is more accountability, since the tokens are unique. For users, there is more control, since you can revoke or deny access rights to one application while granting it to another.
Caution
OAuth is still a work in progress, not just for Twitter but also as a method and movement. By mid-2009, Twitter will be releasing its OAuth to production applications, but that doesn’t mean every application will be inclined or able to use it.
The information returned by Twitter can be refined during the HTTP request. Most API methods accept one or more parameters, most of which are optional but some of which are required. Not all parameters are available to every method.
The Twitter API relies on UTF-8 encoding of all parameter values,
which means you can’t send some special characters as plain text without
confusing the machines that have to deal with that information. This is
particularly important in differentiating between parameter string
connectors, such as & and
=, and the actual values contained
within each parameter. Encoding gives the API a means to distinguish
between the two. Fortunately, most programming languages—including
PHP—have some functions that make encoding parameter values
simple.
Note
Angle brackets (<
and >), double quotes ("),
and the ampersand (&) are
converted to entities as a security precaution against attacks from
web applications. The resulting encoded characters count toward the
140-character limit for Twitter messages.
I have gathered together all of the possible parameters, both required and optional, into one place to give you a convenient reference. Not every API method will accept all of these, but the parameters work the same way for the methods that do recognize them.
For several of the Twitter API methods, it is not enough to just send the URL; the request also requires that some parameter value be included to let Twitter work its magic. The following are descriptions of parameters that may be required for some API methods:
id/user_aanduser_b/userA Twitter user can be referenced using either an integer ID or the username associated with that account. For status or direct messages, the ID must reflect an existing record number. The
id(or similar) parameter is passed as part of the URL request.status/textThe text for a status update or direct message is limited to 140 characters after URL encoding.
locationThe location of the user is not standardized in any way. Any encoded text can be published to the location field in the user’s profile.
deviceThe
devicemust be one of the two valid options supported by Twitter, namelysmsorim. To turn off device notifications, the value should benone.Note
Although this parameter allows for future expansion, in practice it can only be used to turn cell phone messages on or off—Twitter officially discontinued IM support in 2008.
q(Search only.) Although the Keyword Search method will return header information if you don’t include a query string, any API requests without this parameter are almost meaningless. The
qstring must be URL-encoded.
The power and efficiency of the API are increased when you send additional instructions to Twitter to shape what information is returned. In addition to any parameters that a given method may require, there are usually additional options that can be set to filter data before it is returned to you. The following list describes parameters that may be optional for some API methods:
id,in_reply_to_status_idEven when it isn’t required, the value of
idwill still be either an integer ID or the username associated with the account when referring to a person (for user methods), or an existing record number when referencing a message (for status methods). Theidparameter is passed as part of the URL itself, not as a separate query string or POST field value.The
in_reply_to_status_idparameter references the specific status update by another user with which a tweet is associated.emailA user’s email address can be used if you do not know the user ID or username. This parameter is also used to edit the member profile and change which email address is associated with a given account.
user_idThis parameter overrides
id(which can contain either a user ID or screen name) with the ID of the specified member account. It was added to prevent ambiguities when the screen name is a number.screen_nameThis parameter overrides
id(which can contain either a user ID or screen name) with the screen name of the specified member account. It was added to prevent ambiguities when the screen name is a number.sinceThis parameter can be used to limit results to the most recent activity, performing the same function as the
If-Modified-Sinceheader in an HTTP request. This filter ignores information older than the specified time (which must be within the last 24 hours). The value must be encoded to be in the formTue%2C+20+Jan+2009+11%3A30%3A00+GMT.since_idThis parameter functions similarly to
since, except that it filters based on the ID of a specific status update or direct message instead of a date. Twitter returns only the records with IDs greater than the specified value (i.e., records that postdate the message with the specified ID).countFor timeline requests,
countlimits the results to thenmost recent status updates, wherenis the integer value specified in the request. The maximum allowedcountvalue is 200.rpp(Search only.) This parameter (results per page) specifies the number of status messages to return on each page, given a specified search term. The maximum allowed
rppvalue is 100.pageThis integer value paginates the Twitter results for status updates, direct messages, and members of a follow network. For status updates, each page contains up to 20 items. For followers and people you follow, each page holds up to 100 authors. The Keyword Search method also uses this parameter, but it allows the application to dictate (with
rpp) how many of the 1,500 matching tweets are displayed at a time (and therefore how many pages are needed to browse the full corpus).Note
The
pageparameter always begins at 1, which is the default, not 0.followThis is a Boolean value that indicates whether you want to be notified on your cell phone or some other device when the user indicated by the
idparameter posts a status update. This parameter is used to enable notifications at the same time that you begin following a new person.nameThe full name of a member is often more readable and meaningful than the user account handle. This option allows you to change the full name listed on a member account. The maximum length is 40 characters.
urlEach member can associate her account with a single link to a website. This parameter allows you to change the URL listed for a member account. The maximum length is 40 characters.
locationThe location of the user is not standardized in any way: any encoded text not longer than 30 characters can be published to the location field in the profile. This parameter allows you to change the location listed for a given member account.
descriptionThis parameter specifies the text (maximum 160 characters) describing a member or organization using Twitter. This description shows up on the member’s Twitter profile web page.
imageThe background image to display or tile behind your Twitter member profile web page can be controlled with this parameter. The image must be a GIF, JPG, or PNG and cannot exceed 2,048 pixels or 800 KB. For the profile picture associated with all of your tweets, the maximum values are 500 pixels and 700 KB.
profile_background_color,profile_text_color,profile_link_color,profile_sidebar_fill_color,profile_sidebar_border_colorThese parameters control the web page color scheme for a user’s Twitter member profile. Each option must be specified using a valid hexadecimal code (as in “#f09” or “#ff0099”). The colors are set through the
update_profile_colorsmethod (see the section called “Update Profile Colors”) and dictate how most of the text, links, borders, and shading are displayed.show_user(Search only.) When set to
true, this parameter tags the beginning of each tweet that is returned in the search results with a username and a colon (e.g., “kmakice:Writing”).geocode(Search only.) This parameter filters the search results by location, using the self-disclosed location information in the author profiles. The
geocodeparameter has three parts: latitude, longitude, and radius of interest. The resulting comma-delimited string must be URL-encoded, as in39.123456%2C-86.345678%2C10km. The radius must be specified in units of eithermi(miles) orkm(kilometers).lang(Search only.) This parameter filters the search results by language, using an accepted ISO 639-1 code such as
en,es, orfr.callback(Search and JSON only.) A callback allows a program to pass a reference to a dynamic function on the application side. Because we are focusing on XML in this book, we won’t use callbacks.
In late 2007, use of Twitter’s API reached a sufficient level that some throttling of requests had to be instituted. Clients are now permitted only so many requests every 60 minutes, measured from the time the first request is made. The current level is 100 requests each hour, but the limit fell as low as 30 during the worst of the server strains in the summer of 2008.
Two kinds of rate limits are being tracked: authenticated and unauthenticated accesses. When you authenticate with a valid Twitter username and password, the API starts tallying when you use the API and charges requests against the rate limit for that account. When you are able to get data without authentication, requests are tracked for the IP address you’re using.
Note
In theory, this might allow you to double your rate limit to 200 GET requests per hour, provided no authentication is needed for the data you are interested in getting. If you really have need for that many accesses, however, I suggest requesting whitelisting from Twitter, as discussed later in this section.
In general, any method using POST is exempt from rate limiting. This includes any request where the server data is changed, such as requests related to adding or deleting status updates, direct messages, or associations in the follow network.
When a request is made that exceeds an account or IP address’s rate limit, a data response is sent that indicates the error:
/statuses/user_timeline.xml Rate limit exceeded. Clients may not make more than 100 requests per hour.
Until an hour has passed since the first of those 100 requests, no more data will be accessible. A status code of 400 is also returned, providing another indicator that a problem has occurred without it being necessary to parse the XML, JSON, or plain text containing the specific error message.
Note
The search API is currently handled a little differently than the rest of the Twitter API, due to its history as a third-party application (Summize). Future versions of the Keyword Search method may be similarly limited, but for the time being, Twitter simply monitors for abuse and acts on a case-by-case basis. Any rate limits for the search API are “a bit fuzzier” than the main Twitter API and are based entirely on IP address.
To help developers manage their access to the API, Twitter created a special method to return information about the rate limit status of the authenticating account:
https://twitter.com/...imit_status.xml
Requesting this method does not count against the rate limit and can provide useful information about the current maximum, the number of hits remaining in the current hour, and when the clock will be reset (both in absolute clock time and elapsed seconds). The Check Rate Limit Status method is discussed in the section called “API Administration”.
For most uses of the API, developers can work within the rate limit. However, in some cases, an application will require more than 100 requests at a time in order to provide its functionality. Twitter sometimes makes allowances for this by adding user accounts to a whitelist, where limits are raised or eliminated.
If you are developing an application that requires a lot of requests to the API, you can submit a web form (https://twitter.com/...st_whitelisting) and ask Twitter to be considered for addition to the whitelist of high-volume screen names. This will raise your upper limit from 100 to 20,000 API requests per hour.
In the past, Twitter engineers have taken a beating in the blogosphere about their ability (or rather, inability) to keep the service running under stress. Although much of the traffic to Twitter comes from the API, outages have rarely been attributed to API traffic. One of the reasons for that may be the developer community’s willingness to play nice with the servers.
Note
At a gathering of regional API providers, Twitter’s Alex Payne hinted that Ph.D. students grabbing data is the biggest problem APIs face.[65]
In addition to working within the restrictions the company puts on accessing its data, Twitter advises adopting a few other strategies:
- Load the minimum
Get more data only when the action is triggered by user interaction.
- Maintain a local archive
If you will need to request the same kind of information again, look to your local copy first to avoid repeatedly asking for the same content.
- Paginate
Make use of the
pageparameter rather thancount. If you usecount, combine it with thesince_idparameter to retrieve only new information.- Identify yourself
Set the
User-Agentheader in the HTTP request to help engineers troubleshoot your applications.
Finally, give credit where credit is due. A simple “Powered by Twitter” link to the service ties your application back to the larger community. Look at the Terms of Service section in the Twitter API wiki for more information.
Note
The Twitter API wiki organizes the methods differently from the way I do in this chapter. If you want to see a simpler list of methods in structural order, including a summary of parameters you can use, check out the Appendix A, Twitter API Reference.
The best way to learn the Twitter API methods is to try them out as you read through the material in this chapter. One way to test how the API methods work is through the computer command line, using cURL commands:
curlInvoke the cURL connection.
-uusername:passwordAuthenticate with your Twitter username or ID and password. The username can be substituted with an email address, as only one account is associated with each address.
-d status=your+message+hereFor methods that require a POST, this option is needed to get a valid response from Twitter. The text used in conjunction with the POST option sends parameter data to the API to be processed with the request.
https://twitter.com/...thodname.formatProvide the method URI requested from the Twitter API.
Warning
If cURL returns an error when you use an HTTPS request (specifically, “certificate verify failed”), you can disable the verification of the secured certificate by using the
-koption.This is not an ideal solution, though; I include it here only for convenience. Turning off verification of secure certificates can defeat the purpose of HTTPS encryption. It is better to adjust the certificate bundle to include what you need. Visit http://curl.haxx.se/docs/sslcerts.html for more information on how to do this.
These commands can be strung together to produce a new status message in the public timeline, as in:
curl -uusername:password-d 'status=test' https://twitter.com/...uses/update.xml
If cURL is not installed on your system, you can download it from http://curl.haxx.se/download.html for almost any OS. For more information on using cURL, see the section called “cURL”.
If you are hesitant about using command-line cURL to test your Twitter API method requests, there are other options to help you see the HTTP status codes and content passing between your machine and the rest of the world.
Charles (http://www.charlesproxy.com) is a debugging proxy ideal for investigating HTTPS traffic and XML interactions that travel to and from your machine. You can download the software for a free 30-day trial and then pay $50 for the full license. The simplest way to look at the Twitter API responses, though, is probably through a regular browser. Simply type the method request into the browser’s location field. If authentication is needed, the browser will ask for it.
You may find it easier to navigate the API if we focus on which part of Twitter each method affects. The 38 API methods currently maintained by Twitter can be organized into the following operational groups based on what they’re used for:
- Publishing
Changing the content published to Twitter
- The Information Stream
Retrieving and managing the content published to Twitter
- The Follow Network
Managing the people whom you follow and who follow you
- Communication
Exchanging direct messages with other members
- Member Account
Dealing with your Twitter account
- Administration
Negotiating access to the Twitter API
- Search
Looking for keywords in the tweet archives
The sections that follow explore each group, describing how to format requests with each of the API methods and showing some examples of XML output.
Note
Remember that successful requests return an HTTP status code of 200. You can use this to check how you did if you don’t want or need to parse the data response from Twitter.
Twitter is nothing without its 140-character posts, or tweets. The API methods in this category manage the creation and removal of tweets. Quite simply, you can use these methods to publish content to or remove it from the Twitter information stream.
Note
When successful, the publishing methods return status objects. See the section called “Status Objects” for more details about the data that is returned.
This method adds a tweet to the information stream for the authenticated user. In Twitter terminology, this is an update of the current member’s status:
https://twitter.com/...uses/update.xml
To make this URL request function, authentication is required (so that the new status message can be assigned to the correct account). Since it involves a change to the service database and not simply a data grab, the POST method is required to encapsulate the parameter data in this request.
The Post a Tweet method requires one parameter, status, filled with encoded text of no longer than 140
characters. Omitting the message results in no status being published
and subsequently no content being returned. When successful, Twitter
returns XML containing information about the new status update (see
the section called “Status Objects”).
To identify which tool published the tweet—as in “from the web”
or “from twitterrific”—there is
an optional parameter, source, that
can contain the short identifying string registered with Twitter upon
request. There is also an optional parameter, in_reply_to_status_id, that can attach this
tweet to another specific status update by another user. This will
associate the message with the author specified in the in_reply_to_user_id attribute in the status
data object. If the reply status ID is not valid, the parameter will
be ignored.
Warning
Many older Twitter applications assume that a new message sent as a reply is a response to the most recent status update by the targeted author. For active accounts, this can cause replies to be attached to more recent updates than are intended, causing some issues in the integrity of threaded conversation.
Twitter has added elements to support better threading for replies, but the association to the replied-to author’s last tweet is still programmed into many third-party Twitter tools.
After a status update has been published, it can be deleted. However, this can only be done if the authenticated user is also the author of the update to be removed:
https://twitter.com/statuses/destroy/id.xmlThe id parameter is required to identify which existing status update is
to be deleted—information that
is included by referencing the status ID in the request URL (replacing
id in the preceding link). If the request
is successful, Twitter returns the status object information. This is
the same response posting a new tweet will produce (see the previous
section). If the status ID is not provided or is invalid, the XML
returns an error: “No status found with that ID” (see the section called “Hash Objects”).
Deleting a tweet is a practice that should be discouraged. Part of the value of Twitter is that it provides a long-term record of the little things we do and say, including the mistakes. Although there will almost certainly be times when you will need to remove a tweet you’ve posted, it is important to realize that your timeline is not an inbox. Leave your footprints for posterity.
Warning
There are some known issues with deleted status updates still appearing in Twitter searches. This problem should be resolved with the next upgrade to the Twitter API, expected in 2009.
The collection of published tweets creates a flow of information in Twitter. There is a public timeline of updates, fed by all accounts that are not configured to be private streams and are therefore available for anyone to view. Individual members also have their own streams, which they craft by deciding which members to follow.
This section describes the methods used to access different kinds of streams, display details about specific status updates, and manage the bookmarks—called favorites—that mark content of interest.
Note
When successful, the Information Stream methods return status objects. See the section called “Status Objects” for more details.
This method was created to enable us to view the details for a single status update:
https://twitter.com/statuses/show/id.xmlThis type of request returns XML structured in the same way as that returned by the publishing methods described earlier, including a description of the update author as well as the message itself (see the section called “Status Objects”). If the status ID is not provided or is invalid, the XML returns an error.
Note
Remember, you can easily change the format to JSON by editing
the extension used in the URL to request the method, from .xml to .json.
Authentication is not needed, provided the tweet is public. To view protected status updates made by private authors who have authorized you to do so, you must provide a valid username and password.
This method returns the 20 most recent status updates from public accounts in Twitter:
https://twitter.com/...ic_timeline.xml
Authentication is not required and thus retrieval from the public timeline does not count against the API rate limit, even if you do authenticate.
A successful request returns information about the recent status
updates, following the same format and structure as that returned by
the publishing methods, but with multiple status data objects
contained within a XML wrapper (see the section called “Status Objects”).
Note
The public timeline is cached once per minute, so there is no reason to request public tweets more often than that. This means that, with over a million updates posted to Twitter every day, most tweets will slip through the cracks. Twitter has grown too big to capture everything through the main API.
Twitter does offer two other options: a data mining feed that returns 600 tweets per request, and the “firehose” that gives researchers everything coming across the timeline. See the section called “Other Data Options” for more information.
The public timeline is not a complete picture of all Twitter traffic. An estimated 10% of all user accounts are private accounts;[66] those users’ status updates are available only to approved people and are not included in the public timeline. Additionally, Twitter requires that an account be minimally configured to include a custom user icon for it to be part of the public timeline.
Similar to the one for the public timeline, there is a method in the API to retrieve recent tweets from the perspective of a specific user. Calling the View a Friends Timeline method returns the 20 most recent status updates posted by the authenticated user and the authors that user follows:
https://twitter.com/...ds_timeline.xml
This data is the same stuff you’ll see on the home page after logging into the Twitter website. A successful request returns XML structurally identical to that of the data returned by the View the Public Timeline method.
There are several optional parameters that can be used to filter
the data that is returned. Three of them—since, since_id, and count—change the number of status updates returned by
truncating older tweets. The since
parameter gives the API a certain point in time to use as the
cutoff, whereas the since_id
parameter identifies a specific status ID (presumably the last
one your application successfully captured). The count parameter specifies the number of
recent tweets to return. When creating applications that monitor the
activity of an account, these are great parameters to use to avoid
redundancy.
The page parameter allows the application to navigate further back than
just the 20 tweets available on the first page of the friends
timeline. Current restrictions maximize the archive at 200 tweets,
which translates to 10 pages of timeline content.
A third view of the Twitter timeline is the user archive. This stream contains just the tweets published by a single author. The View an Individual Timeline method returns the 20 most recent status updates posted by the authenticated user:
https://twitter.com/...er_timeline.xml
It’s also possible to request another user’s timeline by adding another level to the URL path and identifying that user, as in:
https://twitter.com/.../user_timeline/id.xmlThe id parameter is replaced
with the user’s ID or username. This is the same content one would see
by visiting a member’s Twitter profile page.
Note
If the requested user has a public account, authentication isn’t necessary; simply reference the user ID or username in the request.
Without authentication or inclusion of a public user ID, this method returns a variation of the standard error message: “Authentication required to request your own timeline” (see the section called “Hash Objects”).
Successful requests respond with an array of status data objects
(see the section called “Status Objects”), as is the case with other
timeline methods. The results can be filtered in the same way as those
for the friends timeline, using since, since_id, count, and page.
Replies are status updates that reference another
Twitter member. The convention, culled from the old days of Instant
Relay Chat (IRC), is to precede the username with the @ symbol. Although Twitter wasn’t originally
meant for conversation, many people post status updates as replies to
direct conversation to particular users.
These replies can be viewed as a separate timeline by using a special API method:
https://twitter.com/...ses/replies.xml
This method returns the 20 most recent @ replies addressing the authenticated user.
These will include status updates posted by people the user is not
following if the account configuration is set to include replies from
all users.
Note
Replies are recognized in Twitter only if the reply
indicator appears at the beginning of a tweet. Any @username
references within the body of the status update will not be included
in the replies timeline. However, any reference to a particular user
can be found using the search API (see the section called “Content searches”).
Twitter currently allows retrieval of up to 40 pages, or 800
replies, by using the optional page
parameter. This method also facilitates retrieval of the freshest
replies by recognizing the since
and since_id parameters.
Successful requests return the standard status data object array, as with the timeline methods discussed previously.
In Twitter, you can create a bookmark (called a “favorite”) to mark a status update you want to remember. There is a separate view of the timeline that returns the 20 most recent “favorited” statuses for the authenticated user:
https://twitter.com/favorites.xml
As with the regular user timeline, you can specify an id in the request URL to get a list of
favorites for a user other than the one whose credentials were used to
authenticate to the API:
https://twitter.com/...tes/kmakice.xml
If that user has a public account, the information can be
retrieved without authenticating. Pagination through the page parameter is the only option available
to let the application navigate back to see the full list of all
favorited tweets.
To create a new bookmark, you must specify the ID of the status update to be favorited in the request URL:
https://twitter.com/favorites/create/id.xmlThis command returns a single status data object for the favorite message when successful, and a “Not found” error if the status message doesn’t exist or is inaccessible to the authenticated user. The new favorite will be associated with the authenticated user.
Deleting a bookmark doesn’t delete the status message (how could it, if you’ve marked other people’s tweets as favorites?), but it does remove the flag you have previously set to remind you how much you liked the content. Times change, and you may need to distance yourself from the memory of a particular update. By using this method, you can un-favorite a specified status message:
https://twitter.com/favorites/destroy/id.xmlThe id of an existing message must be included in the request
URL to indicate the message you now want to forget. If you try to
un-favorite a message that doesn’t exist or isn’t currently a favorite
of the authenticated user, a “Not found” error message will be
returned (see the section called “Hash Objects”). Success brings one
last reminder in the form of a single status data object that
describes the message and its author.
Twitter isn’t just about posting updates when you go to lunch. The magic happens when you grow your network of authors to the point where you start benefiting from the collective wisdom of your tweeps. Those you follow and those who follow you together make up your follow network. This section looks at methods that show you who is in your network, how to expand or contract it, and how to protect it from spammers.
Note
When successful, the follow network methods return information about particular Twitter members. See the section called “User Objects” for more details about the data Twitter makes available.
The notable exception is Confirm a Follow, which returns a response object indicating whether or not one person is following another.
People are the main unit of currency in a follow network. Each member contributes to the collective wisdom, by talking about what is important to them at a given moment and also by identifying other people of interest. When you encounter a new person on Twitter, looking at her profile is one way you can decide whether you want to follow her.
The Show Member Profile method gives you all the basic profile information you have already seen attached to the status data objects, plus a lot of new information about the specified user. Most importantly, this is the method you need to use to find out statistics such as the number of updates a user has posted and how many people that member is following:
https://twitter.com/users/show/id.xmlEven to access your own profile information, the id needs to reflect your username or user ID
and be included in the request URL.
Note
The /show part of the URL
isn’t needed. These two URLs return the same results:
https://twitter.com/users/show/id.xml https://twitter.com/users/id.xml
Alternatively, you can use the email parameter to get profile data, as
in:
https://twitter.com/...akice@gmail.com
Doing so allows you to look up a Twitter member’s account
information by referencing the email address used to register that
account (for public accounts, authentication is not required). Private
accounts are protected from this search, unless the authenticating
user has been granted access to those accounts. Twitter also added two
other parameters—user_id
and screen_name—that can identify which member
account you want returned. Either can be used as a query string
variable (e.g.,
https://twitter.com/...xml?user_id=415) to
help disambiguate between user IDs and screen names that are composed
entirely of numbers. id assumes a number is a user
ID and returns that, which made it impossible to view some profiles.
The two newer parameters were added to give you more control and in
fact take precedence over use of id.
Note
Accounts are sometimes disabled. When that happens, the Twitter API will return a status code of 404, rather than showing any profile information for that account.
The detail in the XML gives you a lot of information about the design of the specified member’s profile page, including the style scheme used on the page and whether it has a background tile. Although you may not be too interested in what the member’s profile page looks like, you also get details on the user’s time zone setting, the number of status messages that user has bookmarked (favorites), the total number of updates he has posted, and the number of other people he is following. The profile data also includes information about the member’s latest update (see the section called “User Objects”).
If the request is sent with authentication, a couple of extra fields are available in the XML:
false false
This information has to do with the relationship between the two
Twitter users (the authenticated user and the user identified by the
id parameter). In this example, the
authenticated user is not following the requested user. This
information will appear for unauthenticated requests as well,
defaulting to a following value of
true and a notifications value of false.
Note
For protected accounts, these fields and the embedded short-form status object are not included. This was a bug fix to improve security for twitterers with private accounts. It was revealed when someone used the short-form status object to identify the “billionth tweet,” which was published by a member with a protected account.[67]
The more important half of the follow network is the list of people you follow. Although it is great to have a throng of devoted fans hanging on every word you tweet, your experience with Twitter will be affected much more by the content you see than by how many people read your own tweets.
The API provides a method to show who is contributing to your personal information stream:
https://twitter.com/...ses/friends.xml
The following lists are available for any public account. Simply
including the id
parameter in the request URL (username or user ID) without
authenticating will allow you to look at how another member’s
information stream is composed:
https://twitter.com/...nds/kmakice.xml
Accessing this information for a private account, however, requires not only authentication but also the permission of the account holder, which you gain by virtue of being allowed to follow that user’s status updates.
The View Members Being Followed method returns a list of up to
100 Twitter members that the authenticating or identified user is
following, with the members who have updated most recently appearing
first. If the user is following more than 100 members, you can access
the full list by using the page
parameter to navigate to less active authors. Each successive page
will include the next 100 users, until the list of followed authors is
exhausted.
This method also allows use of the since parameter, which is quite useful for keeping tabs on just the
latest changes to a following list. You can specify a URL-encoded date
and time (no more than 24 hours old) and have Twitter return only the
latest additions. A successful request returns an array of user data
objects (see the section called “User Objects”).
Note
One shortcoming of the API is that you can’t easily
track changes in the network over time. Daily monitoring of an
account using the since option
will let you see how a member’s following list grows over time, but
not how it shrinks.
Each user’s Twitter profile information can be found in the
structured data, including a flag that indicates whether the account
is private ()
and how many followers that person boasts.
The other half of your follow network consists of the people who find the minutiae of your life so interesting that they decide to hang on every word you tweet. Followers are people who include your content in their information streams, and there is a nice method in the API to request the list of followers:
https://twitter.com/...s/followers.xml
A successful request again gets the array of user profile data, but the ordering is different from that of the following list: Twitter currently lists followers according to when they signed up for Twitter, with the newest members appearing at the top of the list.
Warning
The sort order for such lists is subject to change. Pay attention to the Twitter API Change Log for information about adjustments or new parameters, especially if the order is factored into your code.
If you have a large number of followers, it’s likely that while
a lot of information about your new followers will be on the first
page of results, not all of it will be. Any time an established
Twitter user follows you, that information will be buried deep in the
pagination; to find it, you’ll have to use the page parameter.
The list of people who follow you is a much more guarded secret than the list of those you follow. For starters, you must be authenticated in order to view anyone else’s list. If you are not, or if the person whose information you are trying to get has a protected account and is not someone you follow, an authorization error will result:
Not authorized /statuses/followers/cmakice.xml
About half of the members of the Twitterverse will have more followers than people being followed. The latter is in one’s control, but the former is not. For that reason, exploring someone else’s following list—where everyone has been vetted in some minimal fashion—is probably more useful than looking at their followers.
One of the big obstacles facing developers interested in social graphs of Twitter activity is how to identify all the members of a follow network. Until recently, the only way to get a list of everyone following a given member was to loop through multiple requests of the View Followers method. Now, there is an easier way to do this:
https://twitter.com/followers/ids.xml
This method returns a simple XML list of the user IDs of all of the authenticating user’s followers. No other information is included, such as those members’ latest tweets or even their usernames. This method makes it much easier to keep tabs on social relationships, but the trade-off is you don’t get any extraneous information.
Note
User IDs are the preferred way to keep track of Twitter members. Members can change their usernames via the Settings on the main website, but their user IDs will never change.
The Get All Followers method requires authentication. To get a list of followers for someone other than the authenticating user, add that member’s username or ID to the request:
https://twitter.com/followers/ids/id.xmlIf you don’t authenticate with the API request, you’ll get a message like, “Could not authenticate you.”
The same kind of method is available for the other half of the follow network, too. You can get a simple XML list of the user IDs of all the people you choose to follow by making a single API request:
https://twitter.com/friends/ids.xml
This method does not require authentication, unless the person whose list you want to access has a protected account.
Note
A good way to make use of these two social graph methods is to conduct separate lookups for user profile information for only those members your application doesn’t already know about.
To build your follow network, you need a method for adding a friend. This method allows you to do that, as well as to optionally add this person to your notifications list to receive their tweets on your cell phone.
Note
Back in the olden days of Twitter, those you followed were called “friends.” That’s why the API methods use the terminology “create friendships,” even though on the website and elsewhere this action is now referred to as “following.” The next version of the Twitter API will correct this, but thanks to backward compatibility, friends are likely to be a permanent part of Twitter programming.
To follow another user, you need to create a relationship
between the authenticated user and some other user, identified with
the id parameter:
https://twitter.com/...ndships/create/id.xmlWhat comes back when this request is successful is the short-form profile information for the new friend. The request will only be successful, though, if the relationship doesn’t already exist. If you try to follow someone already on your list, Twitter returns an error: “Could not follow user: id is already on your list” (see the section called “Hash Objects”).
There is an optional parameter—follow—that lets you have a two-for-one by automatically
adding your new friend to your notifications list. If this parameter
is present and set to a value of true, this member will have notifications
enabled so you can immediately start receiving her tweets on your cell
phone. This is the same action performed by the Turn On Notification
method described in the section called “Member Account”.
Note
There is often confusion about the difference between the
Follow a Member method and the one dealing with devices (Turn On
Notification). The Follow a Member method establishes the network
relationship but does not by default enable notifications. Members
for whom notifications are enabled (via either the follow parameter to this method or the
Turn On Notification method) form a subgroup of the people you
follow whose content is sent directly to your registered device
(usually a cell phone).
Notifications are useful for having status updates from close friends or family members sent directly to your phone; you can stay in close contact with a select few people and follow many more users casually through the Web or third-party desktop tools.
Following another account has a few side effects. First, that person’s content is included in your information stream. This happens immediately if the account is public, but only after approval if the account is protected.
Note
If you follow a protected account, the response will be nearly identical to the one you
get when following a public account. The only hint you will get that
you have to wait for approval is the presence of true in the XML
output.
Users with private accounts who have not approved you will still appear in your following list, even if you cannot yet see their content.
Second, most accounts are configured to send a notification when a new follower is added. This is an effective way to expand your follow network, because odds are good that someone interested in what you are tweeting will be interesting to you. Conversely, it is possible that the act of following someone will result in that person following you.
Does your new friend tweet too much about Barney the Dinosaur? No problem. Simply unfollow that person to remove his content from your personal information stream:
https://twitter.com/...dships/destroy/id.xmlThe format and response are the same as for the follow request, except you are removing rather than adding a tweep. If you are not already following that member, then Twitter sends an error: “You are not friends with the specified user” (see the section called “Hash Objects”).
Unfollowing is one of the basic rights of a Twitter member and one of the things that makes the experience so rich. The sharing of information on Twitter is technically decoupled, so you can choose to follow someone who doesn’t follow you. Although reciprocation happens frequently, it isn’t a requirement in Twitter as it is in Facebook and other social networks.
Note
You do not get a notification when someone unfollows you. Your first clue that this has happened may be if that user then follows you again, resulting in an alert notification. For a third-party solution to this problem, read about Qwitter in the section called “Tools for the Follow Network”.
No two information streams are alike, and the same goes for users. What might seem to you a paltry rate of tweeting could be overwhelming to someone else. Use the Unfollow a Member method to adjust your flow of status updates, and try not to take it personally when someone chooses not to follow you.
Wading through all of the pages of your follow network lists, or even requesting profile information for another member to find out whether you’re following that person, is an awkward way to investigate the connections in your follow network. Fortunately, Twitter provides a simple method that can be used to check whether one user is following another:
https://twitter.com/...hips/exists.xml
This method requires two variables—user_a and user_b—that contain the user IDs or screen
names for the two Twitter members whose relationship you want to
confirm. For example:
https://twitter.com/...&user_b=kmakice
If the check is successful, Twitter responds with simple output (see the section called “Response Objects”).
If the first user is not following the second—because either the
relationship or one of the users does not exist—the value of the
returned field will be false. If
the users are not included in the request, Twitter will return an
error: “Two user ids or screen_names must be supplied” (see the section called “Hash Objects”).
Since the follower relationship is not coupled (i.e., you can
follow someone who doesn’t follow you), the order of these two IDs is
very important. In an asymmetrical relationship, you will get opposite
results depending on which member is listed first as user_a.
The great thing about Twitter is that you can choose to unfollow anyone you find too annoying, too noisy, or too obsessed with the sweet, sweet taste of Edwardo’s Pizza in Chicago. Sigh. Those aren’t necessarily reasons to block someone, however. A block is a more serious way to distance yourself from another user.
When you block a user, you aren’t blocking her from seeing your updates. A public account is still a public account. Your status updates, the list of people you follow, and your profile information all remain readily accessible to that user. However, blocking does make it impossible for that person to follow you and keeps your Twitter icon off her profile page.
Note
Twitter reportedly monitors blocking, so if a user receives enough blocks, that user’s account will be flagged for investigation.
Blocks should not be used lightly. They are appropriate for the worst account spammers and those who may be personally harassing you. For anything else, you’re only an unfollow away from peace of mind.
The API method to create a block requires authentication and
inclusion of the dissed user’s id
in the request URL:
https://twitter.com/blocks/create/id.xmlIf this action is successful, the short-form profile data object for the blocked user is returned.
If you block another user, that user will not be notified. Twitter is intentionally subtle in how it conveys the action back to the victim of a block: if that person tries to follow you, he will get an ambiguous error on your profile page. However, the API is much more straightforward about what has happened, providing this message: “Could not follow user: You have been blocked from following this account at the request of the user” (see the section called “Hash Objects”).
For private accounts, of course, the de facto state is that everyone is effectively blocked. You can only include a private member’s status updates in your information stream if the private account holder gives you the OK.
All good things must come to an end. This, too, shall pass. What goes around comes around. Pick your colloquialism, but what I’m trying to say is: blocks aren’t permanent.
You can remove a previous block on another user by using a different method in the API:
https://twitter.com/blocks/destroy/id.xmlThis authenticated POST request will find the user account
specified in the URL (id) and
remove the block that prevents that person from following your status
update stream. When successful, it returns the short-form profile for
the specified user.
Imposing a block removes any follower relationships between the authenticated user and the victim of the block, so removing a block on someone you used to follow will not reinstate that relationship—the user will remain out of your stream until you follow her (or she tries to follow you) again. The user will not be informed that the block has been removed; she will only realize this if she’s told or if she tries to follow you again and succeeds.
If you choose to follow someone whom you currently have blocked, the block will be removed automatically. You do not have to explicitly remove the block in order to follow the victim; that happens automatically with a follow request.
Twitter is not a chat client. Although the culture and the technology recognize replies, the contextual nature of each individual information stream makes it somewhat rude to carry on extended 1:1 conversations with another user whose messages may or may not be included in your other followers’ information streams. For such personal communications, the direct message is your friend.
In addition to the public status update channel, Twitter provides a back channel messaging system that allows you to communicate directly with another member. This can be useful for extended exchanges, for personal questions not meant for public consumption, and to facilitate third-party applications without mucking up the information stream.
Note
To send messages directly to and receive messages directly from another user, you must be following each other. So, although status updates are decoupled (even for private accounts), direct messages require a mutual handshake.
This section covers the creation of new messages, the listing of sent and received messages, and the deletion of existing messages.
Note
When successful, the communication methods return information about the Twitter messages. See the section called “Message Objects” for more details about the data Twitter makes available.
A separate tab in the Twitter interface handles the flow of direct messages, which will occur at a much slower rate than status updates. You can set your account to send you direct message notifications via text or email, and clients such as Twitterrific use the API to bring the messages into a single information stream.
There is an API method to list all of the messages the authenticated user has received, which are returned in groups of 20:
https://twitter.com/...ct_messages.xml
This method recognizes some navigation and filtering parameters
to control which page you retrieve (page) and to look for only the most recent
messages (since, since_id).
The returned list is an array of direct message data objects, each with three distinct parts. The information about the message has some overlap with the information for a status update, in that it provides a record ID, the message text, and the creation date. In addition to describing the author, though, it must also report who the recipient is. Embedded in the direct message object is the familiar short-form profile information about both the sender and the receiver of the direct message (see the section called “Message Objects”).
Since direct messages are not as common as status updates, it is not unusual for an account to have no record of direct messages being received. In that case, the API returns an empty object in the XML (see the section called “Response Objects”).
Twitter also lets you keep track of the direct messages you have sent. A second messaging method lets you access your outgoing message archive:
https://twitter.com/...ssages/sent.xml
Similar to the method for listing received messages, this method
returns the 20 most recent direct messages sent
by the authenticated user. The same optional parameters (since, since_id, and page) are available to adjust which part of
the full list of messages is pulled out of the API.
You can create a new direct message using a special method provided by Twitter:
https://twitter.com/...essages/new.xml
This method requires two parameters: the user parameter identifies who will receive your private bit of wisdom,
and the text parameter is your private bit of wisdom. The
message must be URL-encoded and is limited to the signature 140
characters. Like all requests to change the Twitter database, this
method requires a POST.
If successful, Twitter returns a single direct message data object containing the same information described in the communication methods discussed earlier. Mistakes in the format of the request will result in an “Invalid request” error. Because the sender and the receiver of the message must be following each other, Twitter will return an error if that is not the case: “Can’t send direct messages to users who aren’t your friend” (see the section called “Hash Objects”).
You can also send direct messages using the Post a Tweet method:
https://twitter.com/...uses/update.xml
You must start the status
text with d
username to direct the message to the
person you want. This is the same function the text-based commands
perform in Twitter clients.
Not everyone likes to keep a permanent archive of all of the little messages they send and receive. There is no search mechanism for these messages, so it is sometimes helpful to prune out the ones you don’t want to keep (assuming you want to keep any at all).
Deleting an existing direct message is as easy as using another API method:
https://twitter.com/...ssages/destroy/id.xmlThis method follows more or less the same procedures as that of a status update removal: you identify the ID of the message to be removed and authenticate using the account credentials of either the sender or the receiver. If successful, you will get the message information as a data object.
Until recently, only the receiver of a message had the power to delete it. However, you are now also able to delete messages that you yourself sent—the recipients are no longer the only ones with the power to remove your missives from the face of the Twitosphere.
Warning
If you do decide to delete a message, understand that it will disappear from both the sender’s sent message list and the receiver’s received message list. There is only one copy of each direct message, and either person involved in the exchange can remove it.
You can only destroy what has first been created. If you send a request to delete a received message using an invalid ID, Twitter will let you know it can’t do it: “No direct message with that ID found” (see the section called “Hash Objects”).
Surprisingly, there is no method that allows you to retrieve a single direct message. One might expect something like this to work:
https://twitter.com/statuses/show/id.xml https://twitter.com/...-messages/show/id.xml
Attempting such a request, however, results in the following response from the API:
<html><body>You are being redirected.
Help




