Click here to Skip to main content
Click here to Skip to main content

Create a First Web API Service

, 28 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This article will describe how to create a simple Web API service in order to be able to use it later with AngularJS or ASP.NET MVC application for example.

Introduction

Let's say we want to manage a set of projects and tasks and use it from different devices or from different platforms. We will expose our data through a service using Web API, so it could be used using Json file.

Background

In order to be able to understand what is described here, a knowledge of Entity Framework Code First and MVC pattern is required.

Using the Code

In Visual Studio 2013, we will create a WebApi project. Go to New Project and select ASP.NET Web Application as in the screenshot below:

New Project

Since Visual Studio 2013, there is only one template for Web Application. An assistant helps you to choose which type of application you want to create. So give a name to your project, MonService for example and click on OK. In the assistant, select Empty template and add references to Web API before creating project.

This is what your new project looks like:

Ok, so now the project is created, we will create our model. In Models directory, add a new class Project and add the following code in it:

public class Project
{
	public int Id { get; set; }
    public string Name { get; set; }
}

Then, add a Person class:

public class Person
    {
        public int Id { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string FullName
        {
            get
            {
                return string.Format("{0} {1}", FirstName, LastName);
            }
        }
    }

And finally, add a Task class:

public class Task
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime CreatedOn { get; set; }
        public Person CreatedBy { get; set; }
    }

Before going further, let's compile our project to be sure everything went fine.
Ok, so build should be successful as we haven't done something tricky from now. Our model is ready, we now need to implement a method to be able to manage our objects, like create it, select it or delete it.

To do so, we will add a first controller ProjectController to manage our projects. Add a new Controller in the Controller folder choosing Web API 2 Controller with actions, using Entity Framework template.

Configure the controller as below:

The new controller is created. A file named ProjectController appeared in Controller folder and a class named MonServiceContext is added in Models folder. This class is used by Entity Framework Code First to create the context to interact with the database. If you open the class, you can see the name of the connection string that will be used by the project. This name can be modified but if you do so, remember to modify the name in the Web.config file too.

<connectionStrings>
<add name="MonService" connectionString=.../>
</connectionStrings>

You can also notice that a DbSet to manage projects has been created. You can add Tasks and Persons like below:

Build the project, everything should be good.

We have added all we need to manage our project. We will now test it. Run the application. Internet Explorer should be launched and a URL like this http://localhost:3333 should be called. The URL depends on the internal Web server of Visual Studio. When the page is loaded, you get a 403.14 error.

Detailed Error - 403.14 - Forbidden

This is because there are no web pages corresponding to this URL. So, how can we test our service ? Web API allows you to add parameters in the query in order to interact with services. If we want to list all projects, we can add /api/project to the URL (http://localhost:58167/api/project) and refresh the page. This time, Internet Explorer asks you if you want to download or open a file named project.json. Open it. It contains json string with the list of our project. In this case, it is empty as we don't have any project created yet.

DownloadJsonProject

Now modify the URL like this: http://localhost:58167/api/project/1. We are telling the service we want to retrieve the project with Id=1. We get a 404 error, not found. If we take a look at the code in the controller, we can see in the GetProject method that if a project with the Id passed as parameter is not found, then the service should return a Not Found error.

// GET api/Project/5
[ResponseType(typeof(Project))]
public IHttpActionResult GetProject(int id)
{
     Project project = db.Projects.Find(id);
     if (project == null)
     {
        return NotFound();
     }
     return Ok(project);
}

So the application runs as expected.

MethodeGetId

And here we are. We have created your first Web API service and see how to simply test it without any further code or application. You can now add controllers for Task and Person if you wish.

Hope this simple tutorial will help you get started with Web API service. A future article will explain how to use it from other applications, like ASP.NET MVC app or AngularJS.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nadege Rouelle
Architect
France France
I'm coding in .Net since 9 years, most with ASP.Net and SharePoint and a little using WPF, MVC, Windows Phone 8 and WinRT technology.
I have learned so much reading others experience and tutorials, or tips so I try to do the same, keeping learning from others of course.
You can also find my blog here : http://sharemstips.wordpress.com/
Follow on   Twitter

Comments and Discussions

 
QuestionGood Tutorial Pinmembersl8b16-Aug-14 9:36 
GeneralMy vote of 3 PinmemberOshtri Deka28-Feb-14 15:48 
GeneralRe: My vote of 3 PinmemberNadege Rouelle28-Feb-14 22:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141220.1 | Last Updated 28 Feb 2014
Article Copyright 2014 by Nadege Rouelle
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid