DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • Master-Class: Understanding Database Replication (Single, Multi, and Leaderless)
  • Liquibase: Database Change Management and Automated Deployments

Trending

  • 5 AI Security Incidents That Broke Things in Production (and What They Have in Common)
  • Pragmatica Aether: Let Java Be Java
  • GenAI Implementation Isn't Magic — It’s a Lifecycle
  • Alternative Structured Concurrency
  1. DZone
  2. Data Engineering
  3. Databases
  4. Building Server in Julia and Connecting to a Database

Building Server in Julia and Connecting to a Database

Julia has Genie framework which makes building server absolutely easy. Connecting backend to a Database is also included in this article.

By 
Samanway Dey user avatar
Samanway Dey
·
Updated Dec. 09, 20 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
12.7K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

With the growing popularity of the internet, building a web server has been an absolutely required skillset for any developer. However, there are popular frameworks in some languages available (like Node.js or Django) to build the backend. Still, Julia, being a relatively new language, also provides a framework for the same purpose. Julia is still under active development phase and has closer compiler performance to C than other languages.  Developers who have already implemented a machine learning or some data processing algorithm in Julia can now use the Julia Genie framework to expose APIs as well, which would help them use the same stack for the whole backend.

Installing Julia

If Julia is already installed in the system, typing $julia --version in the terminal should give version of Julia installed locally. Otherwise, official Julia documentation can be referred for installation. If installed properly, typing $julia in the terminal should start Julia in REPL mode.

Installing Genie

Installing Genie is the same as installing any Julia library. Typing Pkg.add("Genie") in REPL would install the Genie framework. Importing the package is performed by using Genie.

Getting a Basic Server Running

Let's create a working directory test_server and an empty file named server.jl inside test_server.

Starting a server using Genie is fairly simple. up(port_number, async = false) function starts a server listening to the mentioned port number. Type the following snippet in the server.jl and save.

Julia
 




x
7


 
1
using Genie
2
 
          
3
route("/path") do
4
  return "Hello"
5
end
6
 
          
7
up(8001, async = false)
15
    DBInterface.execute(conn, "INSERT INTO USERS (user_id, user_status) VALUES ('$user_id', '$user_status')")



Now open a terminal from the test_server directory and start Julia REPL. Typing include("server.jl") in REPL would start the server in port number 8001. Opening http://localhost:8001/path in a browser would show the text Hello.

Adding More Routes

Let's take a use case of creating new users and getting a list of all existing users. For this we would need 2 APIs:

  1. One for creating a new user, which would be using the POST method
  2. Another for getting a list of existing users who would be using GET

So, modify the server.jl file with following content.

Julia
 




x


 
1
using Genie
2
 
          
3
route("/createuser", method = POST) do 
4
    return "POST OK"
5
end
6
 
          
7
route("/getusers") do
8
  return "GET OK"
9
end
10
 
          
11
up(8001, async = false)



Accessing Request Parameters

We need to access the parameters and their values sent as payload in request body. To access a parameter we have getpayload(:param_key, "default_value") or postpayload(:param_key, "default_value") depending on whether it is a GET or POST request. Here param_key is the key of the parameter, and default_value is the value that would be considered if the parameter is not set in the request body.

Let's modify our server.jl with the following snippet.

Julia
 




x


 
1
using Genie
2
using Genie.Router, Genie.Renderer, Genie.Renderer.Html, Genie.Renderer.Json, Genie.Requests
3
 
          
4
function createUser(user_id, user_status)
5
end
6
 
          
7
route("/createuser", method = POST) do 
8
    createUser(postpayload(:user_id), postpayload(:user_status, "active")) 
9
    return "POST OK"
10
end
11
 
          
12
route("/getusers") do
13
  return "GET OK"
14
end
15
 
          
16
up(8001, async = false)
9
    return "POST OK"



Installing MySQL

We would be using MySQL for Database. Needless to say MySQL should be installed in system. Otherwise the official installation guide can be followed. Once MySQL server is up and running locally, create an empty database named test_user. From the MySQL command-line client, it would look like this.

mysql

Accessing MySQL Database

We can access and run query in a MySQL server using its Julia client. It can be installed by Pkg.add("MySQL") from Julia REPL. To initiate a connection to server, we can use the following function.

Julia
 




xxxxxxxxxx
1


 
1
using MySQL
2
 
          
3
conn = DBInterface.connect(MySQL.Connection, "localhost", "<user_name>", "<password>", db = "test_user")



This would return a connection object, which can be used to run a query.

Julia
 




x


 
1
cur = DBInterface.execute(conn, sql_query_statmnt)



Connecting the Dots

Summing all the above things up, we can create a Genie server, which would be inserting data to the Database upon creating a new user. To respond to a request of getting to respond query from the database and return the list of users as response.

Our server.Jl would look something like this. Before running the server.jl, install JSON, DataFrames and JSONTables in Julia.

Julia
x
 
1
using Genie
2
using Genie.Router, Genie.Renderer, Genie.Renderer.Html, Genie.Renderer.Json, Genie.Requests
3
using MySQL
4
using JSON
5
using DataFrames
6
using JSONTables
7
8
create_table_sql = """
9
    CREATE TABLE IF NOT EXISTS USERS(
10
        user_id VARCHAR(50) NOT NULL PRIMARY KEY,
11
        user_status ENUM('active', 'inactive') DEFAULT 'active'
12
    );
13
    """
14
15
conn = DBInterface.connect(MySQL.Connection, "localhost", "<user_name>", "<password>", db = "test_user")
16
17
cur = DBInterface.execute(conn, create_table_sql)
18
19
function createUser(user_id, user_status)
20
    DBInterface.execute(conn, "INSERT INTO USERS (user_id, user_status) VALUES ('$user_id', '$user_status')")
21
end
22
23
function getUsers()
24
    cur = DBInterface.execute(conn, "SELECT user_id, user_status FROM users")
25
    df = DataFrame(cur)
26
    stringified_json = arraytable(df)
27
    return stringified_json
28
end
29
30
31
route("/createuser", method = POST) do 
32
    createUser(postpayload(:user_id), postpayload(:user_status, "active")) 
33
    return "POST OK"
34
end
35
36
route("/getusers") do
37
    obj = getUsers()
38
    return obj
39
end
40
41
up(8001, async = false)


Now we are ready to start the server by running include("server.jl").

Requesting Our Server

Our motive will not be complete until we would be requesting our server and get response from it. So for this purpose, we would be using Postman. If not installed, it can be installed following this guide.

Now, we would have to send a POST request on http://127.0.0.1:8001/createuser from Postman. The request body should have two parameters called user_id and user_status. The response should return  the text POST OK.POST OK

To send a GET request on http://127.0.0.1:8001/getusers, no request body is needed. However it is better to set Accept: application/json in our GET request header, so that the server's response is parsed as a JSON. The response should return list of all existing users in our Database.

JSON server

Conclusion

This way, making a basic web server would be pretty easy in Julia; however, to serve a real-world use case will never be this much simple. But, hope this article helps you to have a starting point. Thanks and Happy Coding!

Julia (programming language) Database

Opinions expressed by DZone contributors are their own.

Related

  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • Master-Class: Understanding Database Replication (Single, Multi, and Leaderless)
  • Liquibase: Database Change Management and Automated Deployments

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook