Advanced Xamarin.Forms Part 1 – The API

Spanish Version

In this series, we will explore a number of topics on Advanced Xamarin.Forms that have arisen in our work for clients, or at my job as Principal Mobile Developer for IFS Core.

Before we can start, however, we need to build an API that we can program against. Ideally, this API will support all CRUD operations and will reside on Azure.

Building the API

Begin in Visual Studio, creating an API Core application, which we’ll call BookStore. Change the name of the values controller to BookController. Create a new project named Bookstore.Dal (Data access layer), within which you will create two folders: Domain and Repository.

Install the Nuget package LiteDB a NoSql database. In the BookRepository folder, create a file BookRepository.cs In that file you will initialize LiteDB and create a collection to hold our books.

   public class BookRepository
   {
      private readonly LiteDatabase _db;
      public BookRepository()
      {
         _db = new LiteDatabase("bookstore.db");
         Books.EnsureIndex(x => x.BookId);
      }

If bookstore.db does not exist, it will be created. Similarly if the inidex doesn’t exist, it too will be created.

Go up to the API project and right-click on Dependencies to add a reference to our Bookstore.dal project. Open the BookstoreController file. Add using statements for Bookstore.Dal.Domain and Bookstore.Dal.Repository.

Create an instance of teh BookRepository in the controller, and initialize it.

   public class BooksController : ControllerBase
   {
      private BookRepository _bookRepository;

      public BooksController()
      {
         _bookRepository = new BookRepository();
      }

Creating the Book Object

We will need a simple book object (for now) to send and retrieve from our repository and database. Start by creating the book object (feel free to add more fields)

  public class Book
   {
      public Book()
      {
         BookId = Guid.NewGuid().ToString();
      }

      public string BookId { get; set; }
      public string ISBN { get; set; }
      public string Title { get; set; }
      public List<Author> Authors { get; set; }
      public double ListPrice { get; set; }
   }

Notice that the Book has a List of Author objects. Let’s create that class now, again keeping it very simple,

   public class Author
   {
      public string AuthorId { get; set; }
      public string Name { get; set; }
      public string Notes { get; set; }
   }

The Repository

Let’s return to the repository. Earlier we initialized the database. Now all we need is to create the methods.

We begin by creating the connection of our local List of Book to the db table:

      public LiteCollection<Book> Books => _db.GetCollection<Book>();

Next comes our basic methods: get, insert, update, delete:

 public IEnumerable<Book> GetBooks()
 {
    return Books.FindAll();
 }

 public void Insert(Book book)
 {
    Books.Insert(book);
 }

 public void Update(Book book)
 {
    Books.Update(book);
 }

 public void Delete(Book book)
 {
    Books.Delete(book.BookId);
 }

Connecting to the API

We are ready to create the CRUD methods in the API and connect them to the methods in the repo.

      [HttpGet]
      public ActionResult<IEnumerable<Book>> Get()
      {
         var books = _bookRepository.GetBooks();
         return new 
              ActionResult<IEnumerable<Book>>(books);
      }

This will return the retrieved data to the calling method. Note that this will retrieve all the books.

Following along with using the HTTP syntax, let’s create the Post method:

      [HttpPost]
      public void Post([FromBody] Book book)
      {
         _bookRepository.Insert(book);
      }

Testing

To check that we can now add and retrieve data, we’ll create a Postman collection. Bring up the Postman Desktop App (the Chrome extension has been deprecated), and see or create a Bookstore collection. In that collection will be your post and get methods.

To keep this simple let’s add a book using JSON. Click on Headers and set authorization to applicatoin/json. Then click on body and enter the Json statement:

{"Title":"Ulyses"}

Press send to send this to our local database. To ensure it got there, switch Postman to Get, Enter the url and press send. You should get back your book object.

[
    {
        "bookId": "d4f8fa63-1418-4e06-8c64-e8408c365b13",
        "isbn": null,
        "title": "Ulyses",
        "authors": null,
        "listPrice": 0
    }
]

The next step is to move this to Azure. That is easier than it sounds.


First, go to the Azure site. Select the Start Free button.

The Start Free button

Create an account with your email address and after you confirm your email address you are ready to use the account form in Visual Studio.

Our next step is to publish the API. Select the publish option and select the following steps:

When you are creating the App Service to be used in the hosting plan, you can select the free tier.

After publishing is complete, you will have access to your API in the endpoint you just created. In our example, the endpoint is https://bookstoreapiblogpost.azurewebsites.net/ You can test your new endpoint in Postman and then use it in your project.

Source Code Repository

By Jesse Liberty (Massachusetts US) and Rodrigo Juarez (Mendoza, Argentina)

Rodrigo Juarez is a full-stack and Xamarin Certified Mobile Professional developer working for Belatrix Software. His mission is to solve complex problems for his clients focusing on the results, applying the most adequate technology available and best practices to ensure a cost-effective and high-quality solution. He has 20+ years of experience in a wide variety of projects in the development of applications for web, desktop and mobile using Microsoft technologies in areas such as management, services, insurance, pharmacy and banks.  He can be reached at  Rodrigo Juarez


About Jesse Liberty

Jesse Liberty is the Principal Mobile Developer with IFS Core. He has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in API, Xamarin and tagged , . Bookmark the permalink.