Click here to Skip to main content
15,900,511 members
Articles / Programming Languages / C# 3.5
Tip/Trick

How to make REST requests with C#

Rate me:
Please Sign up or sign in to vote.
4.90/5 (55 votes)
21 Nov 2012CPOL2 min read 557K   93   30
A reusable component for makeing REST service requests using C#

Introduction

REST web services have become mainstream and it is important as a developer to know how to communicate with the onslaught of services built using this architecture which now flood our industry. In this article I will provide you with a module I developed for making web request to REST services using C# and give you some details on how the code works.

Explaining what REST services are and how they work is beyond the scope of this modest article. However, if you are unfamiliar with the basic concepts I recommend you ready this article and get up to speed.

Background

This class I'm going to share with you is one I developed for simplifying RESTful service calls using C#. It has served me well over the years and is in production use all over the place. Hopfully it saves you some time and adds something usful to your arsenal.

Using the code

Using the code is pretty straightforward. You just create an instance of the RestClient class, assign the value of your endpoint (the endpoint is the URL of the REST service you are attempting to call), and call the MakeRequest method.

Basic call

C#
string endPoint = @"http:\\myRestService.com\api\";
var client = new RestClient(endPoint);
var json = client.MakeRequest();

If you want to append parameters you can pass them into the make request method like so.

C#
var json = client.MakeRequest("?param=0");

To set the HttpVerb (i.e. GET, POST, PUT, or DELETE), simply use the provided HttpVerb enumeration. Here is an expample of making a POST request:

C#
var client = new RestClient(endpoint: endPoint, 
                            method: HttpVerb.POST, 
                            postData: "{'someValueToPost': 'The Value being Posted'}");

You can also just assign the values in line if you want:

C#
var client = new RestClient();
client.EndPoint = @"http:\\myRestService.com\api\"; ;
client.Method = HttpVerb.POST;
client.PostData = "{postData: value}";
var json = client.MakeRequest();

The Code

C#
using System;
using System.IO;
using System.Net;
using System.Text;

public enum HttpVerb
{
    GET,
    POST,
    PUT,
    DELETE
}

namespace HttpUtils
{
  public class RestClient
  {
    public string EndPoint { get; set; }
    public HttpVerb Method { get; set; }
    public string ContentType { get; set; }
    public string PostData { get; set; }

    public RestClient()
    {
      EndPoint = "";
      Method = HttpVerb.GET;
      ContentType = "text/xml";
      PostData = "";
    }
    public RestClient(string endpoint)
    {
      EndPoint = endpoint;
      Method = HttpVerb.GET;
      ContentType = "text/xml";
      PostData = "";
    }
    public RestClient(string endpoint, HttpVerb method)
    {
      EndPoint = endpoint;
      Method = method;
      ContentType = "text/xml";
      PostData = "";
    }

    public RestClient(string endpoint, HttpVerb method, string postData)
    {
      EndPoint = endpoint;
      Method = method;
      ContentType = "text/xml";
      PostData = postData;
    }


    public string MakeRequest()
    {
      return MakeRequest("");
    }

    public string MakeRequest(string parameters)
    {
      var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);

      request.Method = Method.ToString();
      request.ContentLength = 0;
      request.ContentType = ContentType;

      if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
      {
        var encoding = new UTF8Encoding();
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
        request.ContentLength = bytes.Length;

        using (var writeStream = request.GetRequestStream())
        {
          writeStream.Write(bytes, 0, bytes.Length);
        }
      }

      using (var response = (HttpWebResponse)request.GetResponse())
      {
        var responseValue = string.Empty;

        if (response.StatusCode != HttpStatusCode.OK)
        {
          var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
          throw new ApplicationException(message);
        }

        // grab the response
        using (var responseStream = response.GetResponseStream())
        {
          if (responseStream != null)
            using (var reader = new StreamReader(responseStream))
            {
              responseValue = reader.ReadToEnd();
            }
        }

        return responseValue;
      }
    }

  } // class

}

How it works

The HttpWebRequest object in the System.Net namespace does all the heavy lifting. It makes the web request and has properties to defign how you want the request submitted across the web. From there I'm reading the response stream and returning it. The rest is just basic class design used to encapselate the functionality into a reusable component. I hope it serves you well Smile | :)

History

  •   11/21/2010 - Posted article w/samples.

License

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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerRe: Authorization Request Pin
Member 1044835919-Nov-14 17:53
Member 1044835919-Nov-14 17:53 
QuestionOracle Procedure for the above code Pin
SHERMIL9-Jun-14 1:13
SHERMIL9-Jun-14 1:13 
QuestionWhy not just use System.Net.WebClient class? Pin
CathalMF10-Feb-14 6:21
CathalMF10-Feb-14 6:21 
AnswerRe: Why not just use System.Net.WebClient class? Pin
freephone6-Jun-14 16:27
freephone6-Jun-14 16:27 
Questionprotocolerror internall error Pin
waqarii20-Jan-14 19:35
waqarii20-Jan-14 19:35 
QuestionGreat!!! Pin
pablojag3-Oct-13 9:53
pablojag3-Oct-13 9:53 
QuestionQuery Pin
oliveLeaf28-Nov-12 0:12
oliveLeaf28-Nov-12 0:12 
AnswerRe: Query Pin
AdamNThompson28-Nov-12 6:40
AdamNThompson28-Nov-12 6:40 
Here is the same class in VB.NET I used a conversion tool to create it so you'll have to try it out and let me know how it goes.

Imports System.IO
Imports System.Net
Imports System.Text

Public Enum HttpVerb
[GET]
POST
PUT
DELETE
End Enum

Namespace HttpUtils
Public Class RestClient
Public Property EndPoint() As String
Get
Return m_EndPoint
End Get
Set
m_EndPoint = Value
End Set
End Property
Private m_EndPoint As String
Public Property Method() As HttpVerb
Get
Return m_Method
End Get
Set
m_Method = Value
End Set
End Property
Private m_Method As HttpVerb
Public Property ContentType() As String
Get
Return m_ContentType
End Get
Set
m_ContentType = Value
End Set
End Property
Private m_ContentType As String
Public Property PostData() As String
Get
Return m_PostData
End Get
Set
m_PostData = Value
End Set
End Property
Private m_PostData As String

Public Sub New()
EndPoint = ""
Method = HttpVerb.[GET]
ContentType = "text/xml"
PostData = ""
End Sub
Public Sub New(endpoint__1 As String)
EndPoint = endpoint__1
Method = HttpVerb.[GET]
ContentType = "text/xml"
PostData = ""
End Sub
Public Sub New(endpoint__1 As String, method__2 As HttpVerb)
EndPoint = endpoint__1
Method = method__2
ContentType = "text/xml"
PostData = ""
End Sub

Public Sub New(endpoint__1 As String, method__2 As HttpVerb, postData__3 As String)
EndPoint = endpoint__1
Method = method__2
ContentType = "text/xml"
PostData = postData__3
End Sub


Public Function MakeRequest() As String
Return MakeRequest("")
End Function

Public Function MakeRequest(parameters As String) As String
Dim request = DirectCast(WebRequest.Create(EndPoint & parameters), HttpWebRequest)

request.Method = Method.ToString()
request.ContentLength = 0
request.ContentType = ContentType

If Not String.IsNullOrEmpty(PostData) AndAlso Method = HttpVerb.POST Then
Dim encoding__1 = New UTF8Encoding()
Dim bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData)
request.ContentLength = bytes.Length

Using writeStream = request.GetRequestStream()
writeStream.Write(bytes, 0, bytes.Length)
End Using
End If

Using response = DirectCast(request.GetResponse(), HttpWebResponse)
Dim responseValue = String.Empty

If response.StatusCode <> HttpStatusCode.OK Then
Dim message = [String].Format("Request failed. Received HTTP {0}", response.StatusCode)
Throw New ApplicationException(message)
End If

' grab the response
Using responseStream = response.GetResponseStream()
If responseStream IsNot Nothing Then
Using reader = New StreamReader(responseStream)
responseValue = reader.ReadToEnd()
End Using
End If
End Using

Return responseValue
End Using
End Function

End Class
' class
End Namespace
-Adam N. Thompson
adam-thompson.com

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.