Web API Tutorial Part I

Introduction

We do not use HTTP just for preparing web pages. We all know that HTTP is a very strong platform for constructing APIs that reveal data and services. HTTP is easy to use, agile, and ever-present. Using API we shall easily communicate with variety of other languages with less code.

Most of the platforms in existence today contain a HTTP library. This enables the HTTP services to extend to a wide variety of clients, consisting of traditional desktop applications, mobile devices, and browsers. We use the ASP.NET Web API framework to build Web APIs on top of the Dot Net Framework.

How to use Entity Framework to Insert, Update, and Delete within ASP.NET WEB API? How to test it using Postman?

Hope Tutors the leading Dot Net Training Institute in Chennai is going to show you in this article how to use Entity Framework to insert, update, and delete within ASP.NET Web API and validating Web API services using Postman.

Create Table

Firstly, we need to create a table in SQL Server to create a CRUD service in ASP.NET Web API. Use the table format as shown below.

Fig 1. Creating table

We have to execute the query as shown in the image below to develop a table with the design shown above.

CREATE TABLE [dbo].[Course]
(
	[CID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](255) NOT NULL,
	[Description] [nvarchar](255) NOT NULL,
	[Cost] [int] NULL ,
	[Syllabus] [varchar](255) NOT NULL,
	[Hours] [smallint] NOT NULL
)

Next, we have to insert some sample records to see the results. In order to do that we need to execute the below query.

Insert into [Course] values ('Photography', 'Photography Description',100,'Avilable',10)
Insert into [Course] values ('Animation', 'Animation Description',100,'Avilable',10)
Insert into [Course] values ('Computer-generated Imagery (CGI)', 'Computer-generated Imagery (CGI) ',100,'Avilable',10)

Create ASP.Net WEB API Project

In this section, we will demonstrate how to create an ASP.NET WEB API Project. We want you to follow the steps as shown below in Visual Studio 2015.

Step 1 – We have to Select Language and Name Your Project

Select New Project > Visual C# > Web > ASP.NET Web Application (Please enter the name of your application here). After this click on OK.

Fig 2. Creating Project in Visual Studio

Step 2 – We have to choose the Empty Web API template and after doing so we need to click on OK for project creation.

Fig 3. Choosing Web Api Template

Step 3 – After clicking on OK, Visual Studio will create the project which contains the basic structure.

Fig 4. Empty Project

Install Entity Framework in your Project

Step 1 - We have to right click on References and after that select Manage NuGet Packages to install Entity Framework.

Fig 5. Installing Entity Framework - 1

Step 2 - After the steps shown above, we need to search Entity Framework online to add and install your project-reference.

Fig 6. Installing Entity Framework - 2


Fig 7. Installing Entity Framework - 3


Fig 8. Installing Entity Framework - 4

Once we are done installing the Entity Framework from NuGet, the assembly references will be added to our project.

Fig 9. Installing Entity Framework - 5

Implementation of the "Database First" Approach with Entity Framework

Before we implement the database first approach, we must all be aware of what the database first model means.

We use the Database First Approach to develop model codes like DbContext, classes, properties, and much more from the project-database. In the Database First Approach, all classes end up becoming the links between the Controller and the database. It normally revolves around the existing database. Now, let us take a closer look at the steps involved.

Step 1 – In this step, we are getting ready to create the ".edmx" file. We are going to create it below the model's folder. We have to right click on the Models folder and then select Add > ADO.NET Entity Data Model.

Fig 10. Creating ADO.NET Entity Data Model - 1

Step 2 – We have to select Data > ADO.NET Entity Data Model > we have to name our edmx file and then click on Add.

Fig 11. Creating ADO.NET Entity Data Model - 2

Step 3 – This step shows us how to configure the connection to the SQL server. In order to create a new connection, we have to click on New Connection option and then choose Microsoft SQL Server. After that, we have to click on Continue to proceed.

Fig 12. Configuring Connection - 1

Fig 13. Configuring Connection - 2

Step 4 – After that, we have to select the table(s) which we need to configure with our application using Entity Framework. After that, we have to click on Finish.

Fig 14. Configuring Database Objects

Step 5 – We can see the image below that the configuration of the HopeTutors1Models is done. We can use edmx diagram to easily view the tables with relationships in case we have more than one table. In this scenario, we are working with a single table.

Fig 15. Edmx Model

Implementation of Web API Scaffolding with Entity Framework

What do we mean by Scaffolding?

Scaffolding helps to automatically generate the code for CRUD operations. We use Visual Studio 2015 to enable the scaffolding option for Web-API and MVC. In order to create Dynamic code for create, read, update, and delete, we will use the dot net in built feature of WEB API with Entity Framework. Let us go through each and every step to understand the process better.

Step 1 – Rebuild the Solution

Fig 16. Building Solution

Step 2 – Controller Creation – Firstly we have to right click on the Controllers folder below our project. Then we have to click on the Add option and then choose Controller.

Fig 17. Controller Creation

Step 3 - If we want to implement the Auto generate Web API Code then we have to select the "Web API 2 Controller with actions, using Entity Framework" option and then click on the Add option.

Fig 18. Creating Api Controller

Step 4 – We have to give a name to the Controller. After doing so, select the Model Class and the Data Context Class and then we have to click on the add option.

Fig 19. Selecting Model Class

If the error is shown then we need rebuild our project and follow Step 3 and Step 4 once again.

Step 4 – In the below-mentioned image we can see that CoursesController creation is done

Fig 20. Scaffolded Controller

Step 5 - Implement Get, Put, Post, Delete, Dispose and IsExists Action method with Logics.

public class CoursesController : ApiController
{
    private HopeTutors1Entities db = new HopeTutors1Entities();

    // GET: api/Courses
    public IQueryable GetCourses()
    {
        return db.Courses;
    }

    // GET: api/Courses/5
    [ResponseType(typeof(Course))]
    public IHttpActionResult GetCourse(int id)
    {
        Course course = db.Courses.Find(id);
        if (course == null)
        {
            return NotFound();
        }

        return Ok(course);
    }

    // PUT: api/Courses/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutCourse(int id, Course course)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != course.CID)
        {
            return BadRequest();
        }

        db.Entry(course).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CourseExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Courses
    [ResponseType(typeof(Course))]
    public IHttpActionResult PostCourse(Course course)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Courses.Add(course);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = course.CID }, course);
    }

    // DELETE: api/Courses/5
    [ResponseType(typeof(Course))]
    public IHttpActionResult DeleteCourse(int id)
    {
        Course course = db.Courses.Find(id);
        if (course == null)
        {
            return NotFound();
        }

        db.Courses.Remove(course);
        db.SaveChanges();

        return Ok(course);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool CourseExists(int id)
    {
        return db.Courses.Count(e => e.CID == id) > 0;
    }
}

Using PostMan to valiate our Services

Postman is a Google Chrome application. We use Postman to interact with HTTP APIs. It helps us with a friendly and simple GUI for developing requests and reading their responses. The organization controlling Postman also offers a complimentary package called Jetpacks. It contains a few automation tools and most importantly, a Javascript testing library.

Step 1: Search for "Postman addon for chrome"

Fig 21. Installing Postman

Step 2: Add it to chrome

Fig 22. Installing Postman

Fig 23. Installing Postman

Step 3: open from chrome (chrome://apps)

Fig 24. Opening Postman

Fig 25. Signing Up

Fig 26. Postman

Step 4: Run the Visual Studio project you will get the below URL (50033 will be auto generated by your visual studio)

API URL: http://localhost:50033/

Fig 27. Running VS

Fig 28. Copy the URL

Step 5: Type the URL in Post Man http://localhost:50033/api/Courses/ and click send.

Fig 29. Configuring parameters in Postman

We could the see the list of json results in Post Man. We could retrieve the JSON data using WebApi.

[
    {
        "CID": 2,
        "Name": "Animation",
        "Description": "Animation Description",
        "Cost": 100,
        "Syllabus": "Avilable",
        "Hours": 10
    },
    {
        "CID": 3,
        "Name": "Computer-generated Imagery (CGI)",
        "Description": "Computer-generated Imagery (CGI) ",
        "Cost": 100,
        "Syllabus": "Avilable",
        "Hours": 10
    },
    {
        "CID": 4,
        "Name": "Cryptography",
        "Description": "Cryptography Description",
        "Cost": 70,
        "Syllabus": "Avilable",
        "Hours": 10
    }
]

Step 6: Now we will insert the data into database using Web Api and Post Man client.

  1. Change the HTTPVerb into POST.
  2. Paste the URL (http://localhost:50033/api/Courses/).
  3. Paste the below content Json in Body Section
{
  "Name": "Cryptography",
  "Description": "Cryptography Description",
  "Cost": 70,
  "Syllabus": "Avilable",
  "Hours": 10
}
  1. Select Raw Option
  2. Select JSON from Drop Down
  3. Click Send you could see the below result.
  4. Place the breakpoint in below "PostCourse " Section.
Fig 30. Inserting data using Postman

See the Magic Model binding in PostCourse Method. Now we have inserted the records into Database using WebApi and PostMan

Fig 31. Method is getting invoked

We could see the "201 Created" in below result. This indicates we have created the new record in database.

Fig 32. API response

Step 7: Follow the below steps to update the record in database using Web API. We are planning to update the CID:1 record.

  1. Select "PUT" option in drop down
  2. Paste the URL http://localhost:50033/api/Courses/1
  3. Select Body then Select Raw Option then Select "JSON"
  4. Paste the Below JSON and click send button
  5. See the Status will have "204 No content". Now the records have been updated.
{
  "CID": 1,
  "Name": "Photography Course",
  "Description": "Photography Description Course",
  "Cost": 100,
  "Syllabus": "Syllabus Available",
  "Hours": 10
}
Fig 33. Testing PUT method

Fig 34. API Response

Step 8: Follow the below steps to delete the record in database using Web API. We are planning to delete the CID:1 record.

  1. Select "DELETE" option in drop down
  2. Paste the URL http://localhost:50033/api/Courses/2
  3. See the Status will have "200 Ok". Now the records has been Deleted.
Fig 35. Testing DELETE

Fig 36. API Response

We've seen how to use PostMan and test the API methods successfully.

Summary

In this article, we saw how to create an ASP.NET Web API service with basic CRUD methods and test them using PostMan. Please use the below comment form for any questions and feedback.

blog comments powered by Disqus