.Net 6 + WebApi Basics 2 - Restful API
2022-12-28 11:21:14  .Net  >> .Net6  >> WebApi

Restful API

There are two basic points to be noted for Restful API.
1. Use HTTP functions to execute CRUD operations.
2. The resources are stored in URL.

Regular URL Format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Create user
http://localhost/createuser

Delete user with id = 1
http://localhost/deleteuser?userid=1

Get user's list
http://localhost/getuser

Get user with id = 1
http://localhost/getuser?userid=1

update user with id = 1
http://localhost/updateuser?userid=1

Restful URL Format with HTTP Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Search users' list
[GET]: http://localhost/user

Search user 1's list
[GET]: http://localhost/user/1

Create an user
[POST]: http://localhost/user

Update user with id=1
[PUT]: http://localhost/user/1

Delete user with id=1
[DELETE]: http://localhost/user/1

For example,
http://localhost/updateuser?userid=1

This address can be seperated into two parts by ?:

URL + ? + Index

Before ?, it is a URL, where stores the resources.

After ?, it is a index, which shows where to find the resources.


Try a Code

Let’s make a trial on the template code of WeatherForcast to understand how the URL and Index are set up.

URL Setup

Comment the Get() function

Comment

Replace with following code

1
2
3
4
5
[HttpGet("GetWeatherForecast/{userid}")]
public string Get(string userid)
{
return userid;
}

Result:
https://localhost:7048/WeatherForecast/GetWeatherForecast/123

code1

In HttpGet attribute, use {userid} to identify the userid in URL. The userid can be set in Get().

Index Setup

Now, replace with following code to see how Index is setup.

1
2
3
4
5
[HttpGet("GetWeatherForecast/{userid}/{index0}")]
public string Get(string userid, string index1, string index2)
{
return userid;
}

Result:
https://localhost:7048/WeatherForecast/GetWeatherForecast/A/B?index1=C&index2=D

code2

Therefore,

Parameters in both HttpGet and Get are specified as URL.

Parameters in HttpGet, but not in Get are specified as URL.

Parameters in Get, but not in HttpGet are specified as Index.

Multiple Index are connected with & after ?.


Next: .Net 6 + WebApi Basics 3

Last: .Net 6 + WebApi Basics 1


Good Day
😎