Click here to Skip to main content
13,668,264 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

8.1K views
10 bookmarked
Posted 9 Jan 2017
Licenced Apache

REST - Overview

, 9 Jan 2017
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

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.

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.

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

And in XML format:

The code on server will be:

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.

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

The code on service will be:

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.

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

On server, we add this code to UsersController:

[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.

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

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.

License

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

Share

About the Author

tranthanhtu.vn
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

You may also be interested in...

Comments and Discussions

 
QuestionHow to go beyond CRUD in a RESTful way? Pin
Bruce Patin10-Feb-17 9:56
memberBruce 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 
GeneralRe: How to go beyond CRUD in a RESTful way? Pin
Bruce Patin13-Feb-17 4:43
memberBruce 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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05-2016 | 2.8.180820.1 | Last Updated 10 Jan 2017
Article Copyright 2017 by tranthanhtu.vn
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid