Programmers T-shirts

Build your own REST API

Updated: Apr 16, 2021

In this tutorial, you will be learned how to create a REST API with the Java Spring boot framework and Postgres DB.

REST API stands for Representational State Transfer Application Programming Interface.

Code: https://github.com/dotanraz/currencies-api


The System

A Currency API that shows currencies prices in USD.

A currency is an object with the following fields:

currencyName and price.

For example:

{

"currencyName: "Euro",

"price": 1.21

}

The API will allow to add a new currency, get all currencies, health check, and test.

Here are the urls for all 4 endpoints:

http://localhost:8080/api/addNewCurrency

http://localhost:8080/api/getAllCurrecnies

http://localhost:8080/api/healthCheck

http://localhost:8080/api/getDummyCurrencies


Main Components

1. Postgres Database to store all Currency prices.

2. Web Server - provide communication over HTTP.

3. Backend - with Java. to process requests, and to fetch and store data from/to the Database.


Tutorial Steps

  1. Download a Spring boot starter project using the Spring Initializr.

  2. Postgres DB Docker Container initialization.

  3. Postgres DB Connection object - handle the communication with the Database

  4. Query Executor class - manage the database queries.

  5. Currency object - a model that describes the currency member fields.

  6. A Currency Service class - manage the exact DB queries that are allowed to be called.

  7. A Currency REST Controller - manage the API endpoints (URLs).


Before we dive into the code, here is a zoom-out snippet on the code we are going to create.

By the end of this tutorial, you should have these files and classes inside your project.


Download a Spring Boot starter project

Go to https://start.spring.io/ and fill in the following details:

  • Project - Gradle Project

  • Project Metadata - use names that describe your company/name and under the Name field use a meaningful name related to the project.

  • Packaging - Jar.

  • Java - I selected Java 8, but you can choose any version you want.

  • Dependencies - search for Spring Web and add it.

  • Generate and extract the files into a folder.


At this point, you should have a working Spring Boot project.

Right-click on MainApplication.java class and Run - the project should run successfully and you should be able to see a webpage at http://localhost:8080.

If the application crashes - make sure port 8080 is not occupied.

If you get a Web Server page not found error - that's ok. we're going to define URLs later in this tutorial.

If you get a Web Server page with a red error - something is wrong. try to generate a new project or search google for solutions.


Postgres DB Docker Container Initialization

This part is strait forward. Just make sure you have Docker installed on your PC.

Start Postgres DB by typing the following command in the Terminal:

docker run -e POSTGRES_PASSWORD=1234 -p 5432:5432 postgres

Note: default user name is "postgres".


Postgres DB Connection object

This class creates a connection to the DB.

It uses the Apache commons BasicDataSource class to define the connection properties.

The class is Singleton - that's because we need it to be initialized only once - on application startup.

I added an environment variable "IP". since, in the production environment, the IP of the DB is not going to be localhost (127.0.0.1).

Make sure to use the same user name and password that was used to startup the Postgres database. Also, by default, Postgres is listening on port 5432.

4. Query Executor class

This class is using the DB connection from the PostgresDbConnection class to execute SQL statements. Any SQL statement must go through this class.

There are 2 methods - one for executing queries that have no return values and one for executing queries that do have return values.


5. Currency object

The Currency class describes the Currency object that is returned by our API.

It has 2 private field members - currencyName & price.

Note: you must create a default constructor that doesn't accept any parameters.

That's since we are going to instantiate this object through the Spring Boot Post method, and under the hood it sets the private members using the setters, and not by passing Constructor's parameters.


Currency Service class

Here we manage the exact DB queries that are allowed to be called.

Each method contains a specific SQL query. The QueryExecutor is in-charge of processing it.

When there is a returned data, it is processed internally by the service method. The response is stored in a proper object model - such as the Currency object.

Notice the @Service annotation - it marks this class as a Service class.


Currency REST Controller

This class manages the API endpoints - the URLs.

For example, the ability to interact with the getAllCurrencies URL (http://localhost:8080/api/getAllCurrencies) is coming from here.

At the class level, we marked this class with the @RestController annotation.

We add the @RequestMapping("/api"). Every URL in this class will start with /api.

You can write any string you want.

Any URL must be defined with an annotation that describes his Http Method - get, post, delete...

For easy understanding, I added a health check method with @GetMapping annotation. When the system is up - any GET requests to http://localhost:8080/api/healthCheck will get a "currency service is up" message as a response.

The GetDummyCurrencies get method is here for testing purpose. it's sometimes faster to interact with it when the database is empty.


The getAllCurrencies method is used to fetch all currencies listed in the database.

It is annotated with the @GetMapping annotation.

It calls the CurencyService.getAllCurrencies() method and passes its results as a return statement.


The addCurrency method is used to add a new currency to the database.

It is marked as a PostMapping. to call it you need to use a developer tool such as Postman.

Notice the (@RequestBody Currency currency). we use it to accept the Currency object in the body of the request. e.g:

{

"currencyName": "AUD",

"price": 0.76

}

Here is an example of a response from the /api/getAllCurrencies url














Wrap Up

Building a REST API system requires lots of development effort.

In this tutorial, we managed to invest the minimum effort to make such a system with persistent data (DB). However, it is mandatory to invest more in adding more capabilities, and optimization - for example, error handling, error codes, and more.


Practical Programming Tutorials for Developers

Work Desk

The SW Developer

The SW Developer was built in order to provide Practical and Simple Tutorials for programmers.

Created by Dotan Raz, Michael Rodov & Kobi Atiya

  • github
  • LinkedIn

Subscribe

Programmers T-shirts