Click here to Skip to main content
15,065,644 members
Articles / Programming Languages / C#
Tip/Trick
Posted 3 Feb 2016

Tagged as

Stats

35K views
1.1K downloads
12 bookmarked

Twitter API for beginners

Rate me:
Please Sign up or sign in to vote.
4.13/5 (9 votes)
3 Feb 2016CPOL1 min read
In this tutorial you can see how to start with C# to Twitter rest api anew

Introduction

In this article I will explain how to start using Twitter api with C# only without any third-party libraries.

This article is intented developers who have basic skills in http/https but have not yet learned REST architecture and OAuth system, or learned already with other services but have problems with Twitter. 

Background

For a start, you need:

- Twitter account (requires email confirmation, and can be full locked without incoming sms verification, but not outgoing)

- Any Visual Studio

Authorize your account in twitter and open https://apps.twitter.com/, click create new app button

Image 1

Provide application name should be unique, description and website URL can be fake:

Image 2

Scroll bottom, accept checkbox and click create your twitter application:

Image 3

You app created, go keys and access tokens tab:

Image 4

Copy the api key and api secret to clipboard:

Image 5

Paste them to notepad in this form:

Image 6

This string should be base64-encoded I using https://www.base64encode.org/ with UTF-8

Encoded string:

Image 7

Encoded string is credentials to get bearer access token for application. Access token should be get programmatically on every application run and should not store anywhere

Using The Code

To send any http requests:

C#
using System.Net;

To work with post requests:

C#
using System.IO;

Do not forgot twitter anywhere supports https requests only not http.

To get bearer access token send http post request and pass credentials to Authorization header

C#
string access_token = "";
var post = WebRequest.Create("https://api.twitter.com/oauth2/token") as HttpWebRequest;
post.Method = "POST";
post.ContentType = "application/x-www-form-urlencoded";
post.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
var reqbody = Encoding.UTF8.GetBytes("grant_type=client_credentials");
post.ContentLength = reqbody.Length;
using (var req = post.GetRequestStream())
{
    req.Write(reqbody, 0, reqbody.Length);
}
try
{
    string respbody = null;
    using (var resp = post.GetResponse().GetResponseStream())//there request sends
    {
        var respR = new StreamReader(resp);
        respbody = respR.ReadToEnd();
    }
    //TODO use a library to parse json
    access_token = respbody.Substring(respbody.IndexOf("access_token\":\"") + "access_token\":\"".Length, respbody.IndexOf("\"}") - (respbody.IndexOf("access_token\":\"") + "access_token\":\"".Length));
}
catch //if credentials are not valid (403 error)
{
    //TODO
}

To exploit any REST api methods send http get or post requests and pass bearer token to Authorization header,

For example you have method https://dev.twitter.com/rest/reference/get/statuses/user_timeline

Your request is

C#
var gettimeline = WebRequest.Create("https://api.twitter.com/1.1/statuses/user_timeline.json?count=3&screen_name=twitterapi") as HttpWebRequest;
gettimeline.Method = "GET";
gettimeline.Headers[HttpRequestHeader.Authorization] = "Bearer " + access_token;
try
{
    string respbody = null;
    using (var resp = gettimeline.GetResponse().GetResponseStream())//there request sends
    {
        var respR = new StreamReader(resp);
        respbody = respR.ReadToEnd();
    }

    //TODO use a library to parse json
    MessageBox.Show(respbody);
}
catch //401 (access token invalid or expired)
{
    //TODO
}

Results

Image 8

Image 9

For more security when app closes send request to invalidate token (to avoid it stolen and used by malware)

C#
var inv = WebRequest.Create("https://api.twitter.com/oauth2/invalidate_token") as HttpWebRequest;
inv.Method = "POST";
inv.ContentType = "application/x-www-form-urlencoded";
inv.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
var reqbodyinv = Encoding.UTF8.GetBytes("access_token=" + access_token);
inv.ContentLength = reqbodyinv.Length;
using (var req = inv.GetRequestStream())
{
    req.Write(reqbodyinv, 0, reqbodyinv.Length);
}
try
{
    post.GetResponse();
}
catch //token not invalidated
{
    //TODO
}

History

02/03/2016: Published first time

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Brahmaputra Mehta
Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
QuestionExcellent Pin
Member 1450381317-Jun-19 21:45
MemberMember 1450381317-Jun-19 21:45 
QuestionThe remote name could not be resolved: 'api.twitter.com' Pin
Brian Herbert9-Jul-17 2:41
MemberBrian Herbert9-Jul-17 2:41 
AnswerUPDATE STATUS IN TWITTER Pin
Romina Mendez4-Dec-16 9:33
MemberRomina Mendez4-Dec-16 9:33 
SuggestionNice Tip Pin
Manas_Kumar3-Feb-16 20:29
professionalManas_Kumar3-Feb-16 20:29 
GeneralRe: Nice Tip Pin
Brahmaputra Mehta4-Feb-16 12:36
MemberBrahmaputra Mehta4-Feb-16 12:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.