Advanced Xamarin.Forms Part 1 – The API

rodrigojuarez

Rodrigo Juarez

Posted on September 12, 2019

Advanced Xamarin.Forms Part 1 – The API

This post is part of an ongoing series that I am writing with @jesseliberty.The original post is on his site and the spanish version on mine.

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);
        }
Enter fullscreen mode Exit fullscreen mode

If bookstore.db does not exist, it will be created. Similarly if the index 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 the BookRepository in the controller, and initialize it.

   public class BooksController : ControllerBase
   {
      private BookRepository _bookRepository;

      public BooksController()
      {
         _bookRepository = new BookRepository();
      }
Enter fullscreen mode Exit fullscreen mode

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; }
   }
Enter fullscreen mode Exit fullscreen mode

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; }
   }
Enter fullscreen mode Exit fullscreen mode

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>();
Enter fullscreen mode Exit fullscreen mode

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);
    }
Enter fullscreen mode Exit fullscreen mode

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);
      }
Enter fullscreen mode Exit fullscreen mode

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);
      }
Enter fullscreen mode Exit fullscreen mode

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"}
Enter fullscreen mode Exit fullscreen mode

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
        }
    ]
Enter fullscreen mode Exit fullscreen mode

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.

Image

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:

Image

Image

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

Image

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)


Image

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.

💖 💪 🙅 🚩
rodrigojuarez
Rodrigo Juarez

Posted on September 12, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Advanced Xamarin.Forms Part 1 – The API
xamarinforms Advanced Xamarin.Forms Part 1 – The API

September 12, 2019