Click here to Skip to main content
13,865,724 members
Click here to Skip to main content
Add your own
alternative version


90 bookmarked
Posted 21 Nov 2012
Licenced CPOL

How to make REST requests with C#

, 21 Nov 2012
Rate this:
Please Sign up or sign in to vote.
A reusable component for makeing REST service requests using C#


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.


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

string endPoint = @"http:\\\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.

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:

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:

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

The Code

using System;
using System.IO;
using System.Net;
using System.Text;

public enum HttpVerb

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 | :)


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


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


About the Author

Web Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionSimple and great, thank you! Pin
Member 104383291-Jun-17 14:19
memberMember 104383291-Jun-17 14:19 
QuestionPasing multiple values to PostData Pin
Member 1265168513-Aug-16 11:27
memberMember 1265168513-Aug-16 11:27 
QuestionUpload Sample code! Pin
Santosh Kokatnur20-May-16 20:54
memberSantosh Kokatnur20-May-16 20:54 
GeneralMy vote of 5 Pin
Parth J Patel26-Apr-16 23:54
professionalParth J Patel26-Apr-16 23:54 
QuestionGetting 403 : Forbidden on hosting in IIS Pin
Vikash RL2-Apr-16 6:36
memberVikash RL2-Apr-16 6:36 
QuestionGood Contribution Pin
Ashok Kumar RV27-Jan-16 0:53
memberAshok Kumar RV27-Jan-16 0:53 
SuggestionSome changes to use with Json Pin
Member 122438948-Jan-16 16:45
memberMember 122438948-Jan-16 16:45 
GeneralVery helpful Pin
Daniel Miller11-Nov-15 7:55
professionalDaniel Miller11-Nov-15 7:55 
QuestionGet data with parameter Pin
banmai_it18-Oct-15 18:32
memberbanmai_it18-Oct-15 18:32 
GeneralMy vote of 1 Pin
abhijeetkpalash9-Jul-15 1:14
memberabhijeetkpalash9-Jul-15 1:14 
QuestionError: The remote server returned an error: (400) Bad Request Pin
Thakur Chandan2-Jun-15 2:17
memberThakur Chandan2-Jun-15 2:17 
SuggestionC# RestClient Pin
Dalsoft23-Mar-15 5:35
memberDalsoft23-Mar-15 5:35 
QuestionI get a URI exception Pin
Dilanka Kalutota26-Jan-15 2:22
memberDilanka Kalutota26-Jan-15 2:22 
AnswerRe: I get a URI exception Pin
DelphiCoder6-Feb-15 23:03
memberDelphiCoder6-Feb-15 23:03 
QuestionVery Helpful Article Pin
Johan Vorster17-Nov-14 5:38
memberJohan Vorster17-Nov-14 5:38 
AnswerRe: Very Helpful Article Pin
chuff030520-Sep-17 5:48
memberchuff030520-Sep-17 5:48 
QuestionRedundancy Pin
Member 1065861322-Sep-14 1:06
memberMember 1065861322-Sep-14 1:06 
QuestionAuthorization Request Pin
KSGRao20-Aug-14 1:22
memberKSGRao20-Aug-14 1:22 
AnswerRe: Authorization Request Pin
Member 1044835919-Nov-14 18:53
memberMember 1044835919-Nov-14 18:53 
QuestionOracle Procedure for the above code Pin
SHERMIL9-Jun-14 2:13
memberSHERMIL9-Jun-14 2:13 
QuestionWhy not just use System.Net.WebClient class? Pin
CathalMF10-Feb-14 7:21
memberCathalMF10-Feb-14 7:21 
AnswerRe: Why not just use System.Net.WebClient class? Pin
freephone6-Jun-14 17:27
memberfreephone6-Jun-14 17:27 
Questionprotocolerror internall error Pin
waqarii20-Jan-14 20:35
memberwaqarii20-Jan-14 20:35 
QuestionGreat!!! Pin
pablojag3-Oct-13 10:53
memberpablojag3-Oct-13 10:53 
QuestionQuery Pin
oliveLeaf28-Nov-12 1:12
memberoliveLeaf28-Nov-12 1:12 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190214.1 | Last Updated 21 Nov 2012
Article Copyright 2012 by AdamNThompson
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid