Click here to Skip to main content
15,867,750 members
Articles / All Topics

REST - Overview

Rate me:
Please Sign up or sign in to vote.
4.78/5 (9 votes)
9 Jan 2017Apache4 min read 14.4K   10   4
Overview of REST

What is REST?

REST is Representational state transfer (REST) in short.
REST itself is not a web-service. it defines the interface/ convention between provider (server/ callee) and consumer (client/ caller).

I Do Not Know About REST, Can I Learn It and How?

Yes, you can learn it. Simply, you should start with the basic CRUD operation for user. This will make it easier for you to understand.

OK, Can You Show Me How to Get a List of Users in REST?

OK, I will show you how to get a list of users in REST, there are some tools needed to install first:

  • Browser: Firefox/ Chorme/ Microsoft Edge. I use Firefox in this case.
  • Install "RESTClient" plug in into your browser. We will use this plug in for sending and receiving request/response to/from server.

The plug in is as below:

Image 1

I assume that user has the following property:

  • First name
  • Last Name
  • Gender
  • Age

We also use these properties around in this article.

For getting the list of users in REST:

Image 2

In this photo, we need to be aware of the following:

  • Url to get the list of users is: <root url>/users
  • Use HTTP Verb: GET
  • Use "Accept" header for specifying type of data want to receive (for example: application/json, ...)

Got It, Can I Use Other Http Verbs (POST, PUT, Delete, ..) For Getting the List of Users Instead of GET?

No, in REST, each HTTP Verb has it own meaning. For example: POST for creating new user, Delete for delete a user, ....

Can I Use Other URL (such as <root url>/users/getUsers) for Getting the List of Users as I Did in .asmx Webservice?

No, in REST, there is a constraint on the name of url. For example: it must be a noun (user) and in plural form (user => users), ...

I See You Mentioned About Constraints in REST, What Are They?

For now, I think we should focus on how to use REST in our API first and we will discuss more about constraints later as it may confuse you.

How About Getting a List of Users on XML Format?

Please change "Accept" header to "application/xml". The result will be:

Image 3

How Many Data Formats (JSOM, XML, CSV, text, ....) Should My REST Support?

This belongs to your business, we can add more or less if needed. The 3 common formats are JSON, XML and CSV.

Which Programming Language, I can implement REST?

Simply, In REST, it defines the interface for interaction between client/server. So we can implement in any programming language, such as: C#, VB, Javascript, Php, Java, Python, ....

And the API should follow the standard of REST, for example: sending "GET" request to my API (http://localhost) with url "http://localhost/users" + accept="application/json" should return the list of uers in JSON format.

Can You Show Me Server Code for Getting the List of Users Above?

Definitely yes, the code was written in C# using WebApi.

C#
namespace WebApi.Controllers
{
    [RoutePrefix("api/users")]
    public class UsersController : ApiController
    {
        private static IList<User> Users { get; set; }
        static UsersController()
        {
            UsersController.Users = new List<User>() {
                new User(1, "User", "1", "Male", 20),
                new User(2, "User", "2", "Male", 20),
            };
        }
        [Route("")]
        [HttpGet()]
        public IList<User> GetUsers()
        {
            return UsersController.Users;
        }
    }
}

In UsersController, I simply define "GetUsers" function that can be called using HttpGet verb, this function will return the list of users as expected (line 15, 16).

Ok, Get the List of Users is Rather Simple, Can You Show Me How to Get User Item?

Yes, it is nearly the same above, with the URL needs to be updated to "<root url>/users/<userId>".

Below is a screenshot of getting user with #1.

Image 4

We noted that the URL in "<root url>/users/1".

And in XML format:

Image 5

The code on server will be:

C#
namespace WebApi.Controllers
{
    [RoutePrefix("api/users")]
    public class UsersController : ApiController
    {
        private static IList<User> Users { get; set; }
        static UsersController()
        {
            UsersController.Users = new List<User>() {
                new User(1, "User", "1", "Male", 20),
                new User(2, "User", "2", "Male", 20),
            };
        }
        [Route("{userId}")]
        [HttpGet()]
        public User GetUser(int userId)
        {
            return UsersController.Users.FirstOrDefault(item => item.Id == userId);
        }
    }
}

How About Creating New Users?

For creating new user, we send POST request to "<root url>/users". The body of request is data we send to server with appropriated value in "content-type" header.

The server uses content-type to recognize format of data and deserialize to appropriated object on server side. It is User object in this case.

Image 6

Get list of users again, we can see new user was added into the list of users:

Image 7

The code on service will be:

C#
namespace WebApi.Controllers
{
    [RoutePrefix("api/users")]
    public class UsersController : ApiController
    {
        private static IList<User> Users { get; set; }
        static UsersController()
        {
            UsersController.Users = new List<User>() {
                new User(1, "User", "1", "Male", 20),
                new User(2, "User", "2", "Male", 20),
            };
        }
        [Route("")]
        [HttpGet()]
        public IList<User> GetUsers()
        {
            return UsersController.Users;
        }
        [Route("")]
        [HttpPost()]
        public User CreateUser([FromBody]User user)
        {
            user.Id = UsersController.Users.Count + 1;
            UsersController.Users.Add(user);
            return user;
        }
    }
}

Ok, Let's Continue with Update User?

To update user, we need to:

  • Send PUT request to server
  • Url in format "<root url>/users/<userId>"
  • Use correct value of "content-type" header for specifying type of data that was sent to server.

Image 8

Get user with #2, we have the following result:

Image 9

On server, we add this code to UsersController:

C#
[Route("{userId}")]
[HttpPut()]
public void UpdateUser(int userId, [FromBody]User user)
{
	User currentUser = UsersController.Users.FirstOrDefault(item => item.Id == userId);
	currentUser.FirstName = user.FirstName;
	currentUser.LastName = user.LastName;
	currentUser.Gender = user.Gender;
	currentUser.Age = user.Age;
}

What about the last operation in CRUD, delete a user?

To delete a user, we need to:

  • Use DELETE verb
  • Send to Url in format "<root url>/users/<userId>"
  • With this operation, we did not need to use content-type as server only need to get userId from client.

Image 10

Get the list again, only 1 item was returned from the API:

Image 11

Where Can I Find the Code for this Article?

Please download it from https://github.com/techcoaching/webapi.

Summary

Now, we have a look at how to perform CRUD using REST in C# (WebApi).

In the next article, we will look deeper into other aspects of REST, such as constraints, performance, ....

If you have any question, write me a comment below, I will answer it as soon as possible.

Thank you for reading.

Note: Please like and share with your friends if you think this is a useful article, I would really appreciate it.
This article was originally posted at http://www.tranthanhtu.vn/post/2016/12/24/webapi-overview

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0


Written By
Architect
Vietnam Vietnam
I have more than 8 years in web development for multiple types of applications (ERP, Education System, ...).
I usually organize training/ coaching on specified topic (such as: RESTful/ WebApi, Angular2, BEM, LESS, SASS, EF, NodeJs ....). Please contact me on Skype (tranthanhtu83) or email (contact@tranthanhtu.vn) if need.
For more information about me, Please visit http://www.tranthanhtu.vn/page/about-me

Comments and Discussions

 
QuestionHow to go beyond CRUD in a RESTful way? Pin
Bruce Patin10-Feb-17 9:56
Bruce Patin10-Feb-17 9:56 
AnswerRe: How to go beyond CRUD in a RESTful way? Pin
tranthanhtu.vn10-Feb-17 21:32
professionaltranthanhtu.vn10-Feb-17 21:32 
Hi Bruce Patin,
Thank for sending me your question.
In search, we also want to get the lit of users. From the view of REST, this action return the list of user.
So we will send request to <base url="" />/users, for filtering parameters, we can pass them as query string or in body of request. this was up to you.
The URL can be in format <baseurl>/users/firstname/techcoaching or <baseurl>/users?firstname=techcoaching.
We have other benefit from query string is that copy and pass the whole querystring, we can get the result as the app does. this was useful for testing purpose.
If we send the filter parameter in body of request, the URI is nice, it hard for test, it was required to use thir-party tool for testing our API, such as: REST client on Firefox/chorme, Postman, ...
The problem we need to aware is the total length of out URI. With long text, we may need to post them as body of request.
Best regards,
TU Tran
Technical Leader
Blog: http://tranthanhtu.vn
Mail: contact@tranthanhtu.vn
Mobile: +84 90 883 884 6
Skype: tranthanhtu83
CodeProject: @techcoaching
LinkedIn: tutrancoaching
Github: techcoaching

GeneralRe: How to go beyond CRUD in a RESTful way? Pin
Bruce Patin13-Feb-17 4:43
Bruce Patin13-Feb-17 4:43 
AnswerRe: How to go beyond CRUD in a RESTful way? Pin
tranthanhtu.vn13-Feb-17 18:37
professionaltranthanhtu.vn13-Feb-17 18:37 

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.