Wednesday 5 May 2021

Part 6 : Exchanging data in Web API

#5 Minutes Of Reading

In this article I will show you, how to pass data to Http methods of Web API or return value from an API.
Http Request helps to pass data to API methods and Http response is responsible to get/returned data from API. I will show you in detail later few articles.
There are several ways to pass data with Http request like query string, route parameter, request header and body. Let’s check all this one by one.
Create Web API application.
Select .net 5.0 target framework shown below.
I have created Index http method. This method gets call with URL
http://localhost:port/api/User
Above url formed with the help of attribute routing, Attribute routing is mechanism where developer can specify cutom URL / virtual path which is even not matching with Api controller name.
Like in below screen I used [Route(“api/[controller]”)] above controller name. you can use any name instead api/[controller]. [controller] automatically replace your controller name.
Click on Get button, it will expand panel and then click on ‘Try It Out’.
Click on Execute and check api response below. I wil show you what is swagger later in this course. For now you can consider it helps to test an API response. In below screen you can see message return from API ‘Hello from API’ with response code 200 and response header highlighted below.
I used string as return type for my Get request, but you can use any valid type or custom type. Will show you how to pass parameter to API method. I’m using Postman tool to test API response shown below.
You can also restrict specific data type like allow only integer value for employee/user id and restrict other type or string.
Let’s see how to pass query string parameter to API.
Reading value from API request header shown in below screen. FromHeader attribute is responsible to read value from request header shown below in highlighted.
In next article I will show you how to bind custom type/class as model.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home