What is REST?
REST is Representational state transfer (REST) in short.
REST itself is no 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 help you easier to understand.
OK, Can you show me how to get list of users in REST?
OK, I will show you how to get list of Users in REST, there are some tools need to install first:
- Browser: Firefox/ Chorme/ Microsoft Edge. I use Firefox in this case.
- Install "RESTClient" plugin into your browser. We will use this plugin for sending and receiving request/response to/from server.
The plugin 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 aware on:
- 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 an 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 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 constraint 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 make you confusing.
How about getting list of users on XML format?
Please change "Accept" header to "application/xml". The result will be:
How many data format (json, xml, csv, text, ....) should my REST support?
this is belong to your business, we can add more or less if need. the 3 common formats are json, xml and csv.
Which programming language, I can implement REST?
Simply, In REST, it define 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 nearly the same above, with the URL needs to be updated to "<root url>/users/<userId>".
Below is 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 dataand 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 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 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
Where can I find more article for REST?
Please have a look:
Summary
Now, we have a look on how to perform CRUD using REST in c# (WebApi).
In next article, we will look deeper in other aspects of REST, such as: constraints, performance, ....
If you have any question, Write me a comment below, I will answer it soon as possible.
CodeProjectThank for reading.
Note: Please like and share to your friends if you think this is use full article, I really appreciate