# Web API Binding

Web API is an application programming interface that uses the [HTTP protocol](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview) to expose data and operations to clients. The Scheduler can use RESTful HTTP requests to perform remote read, create, update, and destroy operations.

For a runnable example, refer to the [demo on Web API binding of the Scheduler component](https://demos.telerik.com/aspnet-mvc/scheduler/webapi) or review the [ASP.NET MVC application](https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/Telerik.Examples.Mvc/Telerik.Examples.Mvc/Areas/SchedulerEditingWebApi) in the [UI for ASP.NET MVC Examples repository](https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master)

## Setting up the Application for Web API Binding

To ensure that the application is configured for Web API binding:

* Configure the Web API by calling `GlobalConfiguration.Configure` in the `Application_Start` method.

  ```C#
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
  ```

* Create a file named `WebApiConfig.cs` into the `App_Start` folder and configure the default Web API routing convention.

  ```C#
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services.
            // Web API routes.
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
  ```

## Adding a Web API Controller

To support writing and reading data using Web API endpoints, the  `ApiController`  base class needs to be inherited for a given controller instance.

```C#
public class TaskController : System.Web.Http.ApiController
    {
        SchedulerTaskService service;

        public TaskController()
        {
            service = new SchedulerTaskService(new SampleEntities());
        }

        protected override void Dispose(bool disposing)
        {
            service.Dispose();

            base.Dispose(disposing);
        }

        // GET api/task
        public DataSourceResult Get([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))]DataSourceRequest request)
        {
            return service.GetAll().ToDataSourceResult(request);
        }

        // POST api/task
        public HttpResponseMessage Post(TaskViewModel task)
        {
            if (ModelState.IsValid)
            {
                service.Insert(task, null);

                var response = Request.CreateResponse(HttpStatusCode.Created, new DataSourceResult { Data = new[] { task }, Total = 1 });
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = task.TaskID }));
                return response;
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage);

                return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
            }
        }

        // PUT api/task/5
        public HttpResponseMessage Put(int id, TaskViewModel task)
        {
            if (ModelState.IsValid && id == task.TaskID)
            {
                try
                {
                    service.Update(task, null);
                }
                catch (DbUpdateConcurrencyException)
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage);
                return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
            }
        }

        // DELETE api/task/5
        public HttpResponseMessage Delete(int id)
        {
            TaskViewModel task = new TaskViewModel
            {
                TaskID = id
            };

            try
            {
                service.Delete(task, null);
            }
            catch (DbUpdateConcurrencyException)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            return Request.CreateResponse(HttpStatusCode.OK, task);
        }
    }
```

## Configuring the Scheduler DataSource for Web API Binding

To enable the CRUD operations that support Web API Binding, explicitly add a `WebApi()` configuration method within the DataSource.  Also, specify explicitly the Web API endpoints by using the `Url.HttpRouteUrl()` extension method.

> Note that a unique identifier for both the `Update` and `Delete` operations is passed as a [`RouteValueDictionary`](https://learn.microsoft.com/en-us/dotnet/api/system.web.routing.routevaluedictionary?view=netframework-4.8.1), which is then processed on the server  as an Action Method argument.

```Razor HtmlHelper
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.TaskViewModel>()
    .Name("scheduler")
    .Date(new DateTime(2022, 6, 13))
    .StartTime(new DateTime(2022, 6, 13, 7, 00, 00))
    .Height(600)
    .Views(views =>
    {
        views.DayView();
        views.WeekView(weekView => weekView.Selected(true));
        views.MonthView();
        views.AgendaView();
        views.TimelineView();
    })
    .Timezone("Etc/UTC")
    .DataSource(d => d
        .WebApi()
        .Model(m =>
        {
            m.Id(f => f.TaskID);
            m.Field(f => f.Title).DefaultValue("No title");
            m.RecurrenceId(f => f.RecurrenceID);
        })
        .Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Task" })))
        .Create(create => create.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Task" })))
        .Update(update => update.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Task", id = "{0}" }))) // Id of the to-be-updated record that will be processed on the server-side.
        .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Task", id = "{0}" }))) // Id of the to-be-deleted record that will be processed on the server-side.
    )
)
```

## See Also

* [Web API Binding by the Scheduler HtmlHelper for ASP.NET MVC (Demo)](https://demos.telerik.com/aspnet-mvc/scheduler/webapi)
* [Server-Side API](https://www.telerik.com/aspnet-mvc/documentation/api/scheduler)
