How to create custom APIs in mobile services (JavaScript backend)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

A custom API in a mobile service is a function that your client apps can call. When you work with mobile services in Visual Studio, you can add a custom API by using the mobile service's node in Server Explorer, and edit the API in Visual Studio. A custom API is created as an HTTP endpoint in the form of a REST API. For example, you can use custom APIs to return data from a query, and to make updates to a database that require more processing than is possible in a simple update script, or involve more than one data table.

If you're using the .NET backend for your mobile service, see How to create custom APIs and scheduled jobs in mobile services.

Prerequisites

Instructions

Step 1: Create a custom API

This step creates a custom API for your mobile service in Azure and opens it for editing in the Visual Studio editor.

  1. In Server Explorer, expand the Azure node, and then expand the Mobile Services node.

  2. Choose your mobile service, open the shortcut menu, and choose Add Custom API.

  3. Enter the name of the custom API, for example, completeall.

  4. Specify the permissions required to access the API.

    Warning  Giving access to everyone allows anyone on the Internet to access your API, which could be a security risk.

     

  5. Choose OK. An editor window opens with the server-side JavaScript code for the custom API.

Step 2: Edit the custom API

You can now write code for your custom API. A custom API can include one or more of the HTTP verbs GET, POST, PUT, PATCH, or DELETE.

  1. Examine the default code that was created for your custom API. This code implements the HTTP verbs POST and GET.

    exports.post = function(request, response) {
        // Use "request.service" to access features of your mobile service, e.g.:
        //   var tables = request.service.tables;
        //   var push = request.service.push;
        response.send(statusCodes.OK, { message : 'Hello World!' });
    };
    
    exports.get = function(request, response) {
      response.send(statusCodes.OK, { message : 'Hello World!' });
    };
    
  2. Replace the code with your own. If you're using the TodoList sample, try this, which sets all items to complete.

    exports.post = function (request, response) {
        var mssql = request.service.mssql;
        var sql = "UPDATE todoitem SET complete = 1 " +
            "WHERE complete = 0; SELECT @@ROWCOUNT as count";
        mssql.query(sql, {
            success: function (results) {
                if (results.length == 1)
                    response.send(200, results[0]);
            }
        })
    };
    

Step 3: Call the custom API from client code

  1. Insert code in the client app to call the custom API. You use the InvokeApiAsync method to call a mobile service. You need a class to hold the result. For this example, the following type will suffice.

    public class CompleteAllResult
    {
        public int Count { get; set; }
    }
    

    For this example code, your client code might look like this in the MainPage class.

    private async void ButtonCompleteAll_Click(object sender, RoutedEventArgs e)
    {
        string message;
        try
        {
            // Asynchronously call the custom API using the POST method. 
            var result = await App.MobileService
                .InvokeApiAsync<CompleteAllResult>("completeAll", 
                System.Net.Http.HttpMethod.Post, null);
            message =  result.Count + " item(s) marked as complete.";
            RefreshTodoItems();
        }
        catch (MobileServiceInvalidOperationException ex)
        {
            message = ex.Message;                
        }
    
        var dialog = new MessageDialog(message);
        dialog.Commands.Add(new UICommand("OK"));
        await dialog.ShowAsync();
    }
    
  2. To complete this example with the sample project, edit MainPage.xaml to add a button that calls the previous code when clicked.

    <StackPanel Orientation="Horizontal">
        <Button Margin="72,0,0,0" Name="ButtonRefresh" 
                Click="ButtonRefresh_Click">Refresh</Button>
        <Button Margin="12,0,0,0" Name="ButtonCompleteAll" 
                Click="ButtonCompleteAll_Click">Complete All</Button>
    </StackPanel>
    
  3. If you're using the TodoList sample, you might also want to update the code to filter out completed items, so you can see the effect of this custom API.

    private async void RefreshTodoItems()
    {
        //// TODO #2: More advanced query that filters out completed items.  
        items = await todoTable 
           .Where(todoItem => todoItem.Complete == false) 
           .ToCollectionAsync(); 
    
        ListItems.ItemsSource = items;
    }
    
  4. Now build and run the sample, and test the Custom API by clicking on the button you added.

Custom API

Call a Custom API from a Windows Store client