Over a million developers have joined DZone.

Raspberry PI + Nancy + (Optional MySQL) = Build a Tiny Embedded HTTP Based Service

DZone's Guide to

Raspberry PI + Nancy + (Optional MySQL) = Build a Tiny Embedded HTTP Based Service

· IoT Zone
Free Resource



In this article we will see how to setup and use Nancy (it’s a lightweight, low-ceremony, and framework for building HTTP based services on .Net and Mono) in Raspberry PI.

The main idea behind using Nancy for building HTTP based services than using Web API or other mechanism, is the simplicity of Nancy.

As the creators of Nancy say, it just works and you don’t really have to worry about configuration changes etc. There is no burden in setting up Nancy and hosting our application in Linux.

If you are a beginner to Nancy, it is highly recommended to have some understanding on the same. You can read from the below link.


This article makes use of a sample MySQL database from the below mentioned link.


It has a basic set of real world data models using which we will be developing a simple and elegant HTTP based service using Nancy and host the same on Raspberry PI.

Our goal is to first setting up the required software – MySQL, Nancy on Raspberry PI. Then we will be creating a simple Nancy application to make the MySQL data available to outside world through Nancy HTTP based service. When it comes to hosting our application, in order to make things simple, we will be hosting our demo app on console.

Later we will be testing the same by making an HTTP Request with the content type set appropriately to show the data in JSON or XML format.

The first thing we do is installing MySQL server on Raspberry PI. Just run the below mentioned command on the Linux console.

sudo apt-get install mysql-server

It will take a while to download and install. But one thing to remember, when you are asked to enter a "New password for the MySQL for the "root" user", enter a password and then confirm the same.

Next, we will be connecting mysql with the root user by running the following command in shell.

mysql -u root -p


You can execute the script file to create database and load sample data by running the following command

mysql> source file_name
mysql> \. file_name

Below is the snapshot where you can see, I am running the script file from “/home/pi/webservices/NancySample1/” location.


Let us take a look into setting up Nancy. Make sure, you have installed Mono as it is required for running Nancy. You can run the following command to install Mono.

sudo apt-get install mono-complete

We will be downloading and compiling the Nancy code on Raspberry PI. Below are the steps that you will have to follow. Note – I have just reused the commands from the below mentioned documentation. Feel free to have a look into if you wish to know more.


mkdir /home/pi/code (or any other directory you prefer)
cd /home/pi/code
sudo apt-get install git ruby rake
sudo gem install albacore --version "1.0.0.rc2"
git clone https://github.com/NancyFx/Nancy.git
cd Nancy
rake mono

You will definitely encounter an error while running the last command for “rank mono”. As the documentation says “The gem albacore version 0.3.5 has a depency bug with rubyzip”. Please follow the below steps to install the right version of albacore.

sudo aptitude install ruby1.9.1-dev
cd ~/code/
git clone https://github.com/Albacore/albacore.git
cd albacore
gem build albacore.gemspec
sudo gem install albacore-2.3.1.gem

The entire installation will take some time. Please have some patience to get these things installed on your PI.

Few more things to get started in coding a HTTP based service using Nancy.

  1. Make sure the MySQL service is started by running the below command.
sudo service mysql restart
  1. This one is optional. Say if you are interesting in remotely accessing the MySQL database installed in Raspberry PI, Please follow the below step.

You have to edit the MySQL configuration file and make a change to binding address from to

Run the below command to do the same.

sudo nano /etc/mysql/my.cnf

After making the above change, save the configuration file and exit out of the editor and run the below command to restart the MySQL service.

sudo service mysql restart
  1. Next step is to grant access to remote connection. For that you need to create a user and then explicitly grant the required permissions for the same. You have to log on to MySQL with the root user (mysql -p -u root ) and execute the below ones by specifying the database name , username and password.

           flush privileges;

It’s the time to code the most exciting thing. That is the Nancy based HTTP Service. I am making use of Visual Studio, to be specific VS 2010 to code this sample application.

Create a console application and install a NuGet package for self-hosting of the Nancy based HTTP Services.

PM> Install-Package Nancy.Hosting.Self
Attempting to resolve dependency 'Nancy (≥ 0.23.2)'.
Installing 'Nancy 0.23.2'.
Successfully installed 'Nancy 0.23.2'.
Installing 'Nancy.Hosting.Self 0.23.2'.
Successfully installed 'Nancy.Hosting.Self 0.23.2'.
Adding 'Nancy 0.23.2' to NancySample1.
Successfully added 'Nancy 0.23.2' to NancySample1.
Adding 'Nancy.Hosting.Self 0.23.2' to NancySample1.
Successfully added 'Nancy.Hosting.Self 0.23.2' to NancySample1. 

The next step is to install MySQL.Data, which is an ADO.NET driver for MySQL.

PM> Install-Package MySQL.Data

Let us start our Nancy sample application by creating the below mentioned entities.

public class Customer
        public int CustomerNumber { get; set; }
        public string CustomerName { get; set; }
        public string ContactLastName { get; set; }
        public string ContactFirstName { get; set; }
        public string Phone { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public double CreditLimit { get; set; }

public class Employee
        public int EmployeeNumber { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Extension { get; set; }
        public string Email { get; set; }
        public string OfficeCode { get; set; }
        public string ReportTo { get; set; }
        public string JobTitle { get; set; }

Building an HTTP based service with Nancy is simple by making your class to extend from NancyModule. Below is code snippet where you can see how the code is being setup to respond when an HTTP request is made to get all customer information or customer info by Id etc. 

public class Program : NancyModule
           public Program()

           void GetCustomers()
               // Get all customers
               Get["/customer"] = _ =>
                   var customerRepository = new CustomerRepository();
                   var customerCollection = 
                       customerRepository.GetCustomerInfo("select *from customers");
                   return Negotiate

           void GetCustomerById()
               Get["/customer/{id}"] = parameters =>
                   int id = parameters.id;
                   var customerRepository = new CustomerRepository();
                   var customerCollection = customerRepository.GetCustomerInfo(
                       string.Format("select *from customers where customerNumber={0}", id));
                   return Negotiate

           void GetEmployees()
               // Get all employees
               Get["/employee"] = _ =>
                   var employeeRepository = new EmployeeRepository();
                   var employeeCollection = 
                       employeeRepository.GetEmployeeInfo("select *from employees");
                   return Negotiate

Here’s the code snippet for hosting our sample Nancy application on console.

static void Main()
          Console.Write("Starting server...");
          var server = new Nancy.Hosting.Self.NancyHost(new Uri("http://localhost:8282"));
          Console.WriteLine("press any key to exit");

Below is the code snippet for Customer Repository, which does nothing more than returning a collection of customer information based on the specific SQL. The code is self-explanatory; we will be opening a MySQL connection with the connection string defined in the application configuration. Then execute a SQL command and use a MySQL data reader to loop through and read customer information.

public class CustomerRepository
        public List<Customer> GetCustomerInfo(string sql)
            string sConnectionString = ConfigurationManager.AppSettings["DbConnectionString"];
            var customerCollection = new List<Customer>();

                using (var dbConnection = new MySqlConnection(sConnectionString))
                    var dbCommand = new MySqlCommand(sql, dbConnection);
                    var dbReader = dbCommand.ExecuteReader();

                    while (dbReader.Read())
                        customerCollection.Add(new Customer
                            CustomerNumber = dbReader.GetInt32("customerNumber"),
                            CustomerName = dbReader["customerName"] is DBNull ? "" : 
                            ContactFirstName = dbReader["contactFirstName"] is DBNull ? "" : 
                            ContactLastName = dbReader["contactLastName"] is DBNull ? "" :
                            AddressLine1 = dbReader["addressLine1"] is DBNull ? "" :
                            AddressLine2 = dbReader["addressLine2"] is DBNull ? "" :
                            City = dbReader["city"] is DBNull ? "" : 
                            State = dbReader["state"] is DBNull ? "" :
                            PostalCode = dbReader["postalCode"] is DBNull ? "" : 
                            Country = dbReader["country"] is DBNull ? "" : 
            catch (MySqlException ex)
                Console.WriteLine("Error: {0}", ex);

            return customerCollection;

Below is the code snippet for Employee Repository. 

public class EmployeeRepository
        public List<Employee> GetEmployeeInfo(string sql)
            string sConnectionString = ConfigurationManager.AppSettings["DbConnectionString"];
            var employeeCollection = new List<Employee>();

                using (var dbConnection = new MySqlConnection(sConnectionString))
                    var dbCommand = new MySqlCommand(sql, dbConnection);
                    var dbReader = dbCommand.ExecuteReader();

                    while (dbReader.Read())
                        employeeCollection.Add(new Employee
                            EmployeeNumber = dbReader.GetInt32("employeeNumber"),
                            FirstName = 
                               dbReader["firstName"] is DBNull ? "" : dbReader.GetString("firstName"),
                            LastName = 
                               dbReader["lastName"] is DBNull ? "" : dbReader.GetString("lastName"),
                            Email = dbReader["email"] is DBNull ? "" : dbReader.GetString("email"),
                            Extension = 
                               dbReader["extension"] is DBNull ? "" : dbReader.GetString("extension"),
                            ReportTo = 
                               dbReader["reportsTo"] is DBNull ? "" : dbReader.GetString("reportsTo"),
                            JobTitle = 
                               dbReader["jobTitle"] is DBNull ? "" : dbReader.GetString("jobTitle")
            catch (MySqlException ex)
                Console.WriteLine("Error: {0}", ex);

            return employeeCollection;

Now it’s the time to run or application executables on Raspberry PI. Here’s what you can do. Compile the application from your desktop/laptop, and then make use of FTP client like FileZilla to establish an FTP connection to your PI. Once you have successfully connected, you can copy all the required executables.


You can either use Putty application or if you have already connected Raspberry PI to a monitor with a keyboard and mouse, you can navigate to executable directory and simply run the console hosted Nancy application from within the shell by running the below command.

mono NancySample1.exe


Now let us search for ‘DHC - REST/HTTP API Client’ chrome extension and install the same. It’s a great tool for making a HTTP Request.

Below is the snapshot you can see on how we are going to make a simple HTTP Request with a content type set to ‘application/json’.

Note – Please make sure to make a note on the IP Address of your Raspberry PI, by using executing “ifconfig” from within the shell. 


I heard about Nancy a few months back. But I never thought I would be using in Raspberry PI experimental projects. It was really exciting to build a simple service in no time. I really appriciate the simplicity of Nancy.


Published at DZone with permission of Ranjan Dailata. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}