Warehouse management REST API with Java & Spring Boot

Overview

Spring Warehouse

Java Spring Boot PostgreSQL Docker JIB Codacy Badge Codacy Badge GPL licensed

Spring Warehouse is a Java Spring Boot REST API that has the purpose of managing products and articles in your warehouse.

This project has been created in an effort to provide an up-to-date example of using the best practices of Java 17 and Spring Boot with Data JPA and Liquibase and being a reference project, similar to Spring Pet Clinic.

You will also find in this repository a docker-compose.yaml which will set up a stack in your machine with PostgreSQL. This project has been developed with horizontal scalability in mind.

Take a moment to read the contributing guidelines and participate in this project in technical and non-technical ways.

Feel free to join the Discord server for Spring Warehouse here for any ideas, support request, or for a friendly chat.

Table of contents

Spring Warehouse logo

Technologies used

This project was built using:

Documentation

To view the API Swagger documentation, start the application and see:

You can view the API specification by using Postman, see the collection here and learn how to use the application endpoints.

Functionalities

In summary the application can:

GET

  • Retrieve a paginated list of products
  • Retrieve a product by UUID
  • Retrieve a paginated list of articles
  • Retrieve an article by UUID
  • Retrieve a paginated list of transactions
  • Retrieve a transaction by UUID
  • Retrieve a paginated list of categories
  • Retrieve a category by UUID
  • Retrieve a paginated list of users
  • Retrieve a user by UUID

POST

  • Add articles
  • Add categories
  • Add products
  • Login and obtain session cookie
  • Register as READ_ONLY user (admins should be created by editing the DB manually)

PATCH

  • Edit product
  • Edit article
  • Edit category
  • Sell products (reserve stock if enough stock is present) or product is unlimited stock like software, this will log every sale of products (transactions)

DELETE

  • Delete product by UUID
  • Delete article by UUID
  • Delete category by UUID

Running the application's dependencies

You should be running on a machine with Docker installed. Clone the project, or download the zip file with the source code from the releases' page.

In the root folder of the project, run docker-compose up -d for starting a database with daemon behaviour (running in the background and even started at system boot) for your database. This should set you up with a PostgreSQL instance running on your machine, configured with the default credentials.

The default credentials are: database warehouse_db, user warehouse_user, password warehouse_user_password.

IMPORTANT make sure that port 5432 of the machine is available and there are no other DB instances using it.

Running for development

IntelliJ IDEA is recommended for this project. This IDE will automatically detect it's a Spring application and provide you with a runnable configuration. For more options see all the available Gradle tasks of this project with ./gradlew tasks.

You can start it with ./gradlew bootRun.

This project uses the jib tool to build deployable images and docker images too. This makes it easy to deploy it to the Cloud and to build prepared images.

The application requires 3 environment variables to be present when running. There are several ways to go about this and you should choose what suits your workflow better.

My default approach is for local development, create a file called .env at the root of the project with the content:

SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/warehouse_db"
SPRING_DATASOURCE_USERNAME="warehouse_user"
SPRING_DATASOURCE_PASSWORD="warehouse_user_password"

then load the variables with source .env. If you run the project via IntelliJ make sure to add the .env file in the run configuration by checking Enable env file and then adding a valid .env file.

This approach using environment variables makes it easier to deploy this to the cloud / other environments since we control the database connection / other variables from the running environment.

If you would like to create and run a Docker image of Spring Warehouse locally run:

./gradlew jibDockerBuild --image=<wanted name for the image>
docker run -it <wanted name for the image>

For publishing to the Google Cloud Registry it is as simple as ./gradlew jib. This step could easily be automated and integrated into the CI / CD pipeline with GitHub Actions.

Domain information

Products are composed of 0 or more articles. Products that are composed of articles can be sold only if they are in stock. Products that are not composed of any article can always be sold. This is in order to take into account that the product is of "infinite stock".

A list of transactions performed (sales) that have occurred can be obtained via the API.

Bear in mind if you want to add new products, the articles which compose the product and the category to which the product belongs to should obviously already be present in the database.

This application includes a graceful shutdown mechanics and so whenever you stop it, or it receives a stop signal, it will first wait for any HTTP request currently being processed to be finished and then gracefully shutdown. This makes it possible to deploy it without downtime and to ensure a better experience for users.

The code has been written in an attempt to achieve as clean code as possible, with dependency injection of key components and with simplicity in mind, with no global state and trying to use functional programming approach where beneficial.

Unit tests

You can run the unit tests for this project if you have Java 17 and Gradle installed, by at the root of the project executing:

./gradlew test

The unit tests will also be run every time the Docker image is rebuilt.

Authentication and Authorization

This REST API is only accessible for authenticated users. Authentication is done by means of an HTTP cookie. You can register users via the API, and posteriorly login also via the API. This will create READ_ONLY users, which are only allowed to perform GET calls to the API. If you want to create an ADMIN account you will need to modify a database record for a user and turn him into admin. That user will have then permission to perform all CRUD operations on all resources, and even create / edit users of all kinds.

Possible Improvements

Some compromises were made during development to simplify certain aspects and make the project quicker to develop. Find some suggestions for improvements below. When better defined, these should be turned into GitHub issues to better keep track of the progress and create separate branches for the features.

  • The docker compose file contains "secrets" which for a production-ready application is not great. Either the file should be encrypted in a certain fashion or the secrets should be obtained from a Vault (Hashicorp Vault comes to mind).
  • Distributed tracing would be a good addition to the application specially if it were to communicate with more services in its operations. Personal choice would be Jaeger.

Front-ends

Due to Spring Warehouse being a REST API this means we can build all kinds of front-ends around it, whether web, native, mobile, etc. This also serves the purpose of allowing developing our skills further and exploring more technologies, due to the de-coupled nature.

Find some honorable mentions below:

Deploying

For learning purposes I created a possible infrastructure running fully on Google Cloud, designed with Terraform. This will setup a Google Kubernetes engine cluster and a PostgreSQL Cloud SQL instance too. We can then learn further on how to deploy a Java application into the cluster.

Comments
  • Package structure & cleaner architecture

    Package structure & cleaner architecture

    As suggested in https://www.reddit.com/r/java/comments/rqqvbh/spring_warehouse_a_quest_to_learn_more_java_and/ by u/nuthrecht it is indeed a better approach to group things by domain instead of by sock-drawer approach. So instead of having controller, model, repository packages, we should group by products, articles, etc.

    enhancement good first issue 
    opened by averageflow 5
  • Constraint validations for request objects

    Constraint validations for request objects

    I saw there is an issue for validating constraints on requests, so I decided to add some of them into the code via Spring-boot annotations, such as @NotEmpty for Iterable objects and so forth.

    opened by gnomo-magico 4
  • Improve sales event

    Improve sales event

    When a sale request occurs, some important things should occur:

    • Stock should be decreased in the correct amount
    • A new transaction record should be created, that contains info about the user performing the sale and also the products and amounts contained in that sale
    • Only ADMIN users should be able to perform a sale
    enhancement 
    opened by averageflow 3
  • Add delete method for users

    Add delete method for users

    Solves issue #45

    https://user-images.githubusercontent.com/80984726/149117213-146834cc-f5d4-4096-8087-74d47462bdf6.mov

    As I mentioned on the issue, I connected the service and it works for 'ADMIN' users

    If you have comments about it please let me know 😄 thanks!

    opened by Artumira96 1
  • DELETE method for deleting users

    DELETE method for deleting users

    Hello, I thought we could add a DELETE method for deleting users, this should be restricted to users with the 'ADMIN' role and by providing the 'uid' in the path:

    image

    I see there's already a service for this so we can connect it.

    enhancement 
    opened by Artumira96 1
  • change application properties format to yaml

    change application properties format to yaml

    • fixes #41
    • add application.yml and application-docker.yml
    • remove application.properties and application-docker.properties
    • change properties file name in Dockerfile
    opened by Silvers-J 1
  • Request validation improvements (#30)

    Request validation improvements (#30)

    • change Iterable to Collection as @Valid doesn't support Iterables
    • add error handling controller advice to handle method argument not supported exception throws by @Valid. Eg response [ { "fieldName": "products", "message": "must not be empty" } ]
    • add whitespaces in application.properties
    • add bin/ to gitignore
    opened by Silvers-J 1
  • Add request validations

    Add request validations

    All requests that contain a body should be validated and Spring Boot validation is perfect for it:

    https://reflectoring.io/bean-validation-with-spring-boot/

    https://www.baeldung.com/spring-boot-bean-validation

    enhancement help wanted good first issue 
    opened by averageflow 1
  • Create response objects instead of returning models

    Create response objects instead of returning models

    We're exposing database entities directly in the controllers, which is a big no-no. Controller, business logic and data should be separate layers and mapped between them. Otherwise you're just ending up with APIs that just expose tables instead of APIs that deliver features. In addition database entities often have fields you want to keep internal.

    We must create response objects which will be used in all responses

    enhancement 
    opened by averageflow 1
  • Use records where possible

    Use records where possible

    Java 17 intrroduced record classes. These reduce boilerplate and simplify data-carrying simple POJOs. This will help cleanup the code.

    https://docs.oracle.com/en/java/javase/17/language/records.html

    enhancement good first issue 
    opened by averageflow 1
  • Category for products & articles

    Category for products & articles

    Products and articles should each have their own categories. Suggestion is to create a few tables:

    • product_categories
    • article_categories

    And the addition of a category_uid field both in article and product entities.

    opened by averageflow 1
  • Add JavaDoc to all classes and methods

    Add JavaDoc to all classes and methods

    We should add JavaDoc to all classes and methods for code quality and documentation purposes. This does not include unit / integration tests, but if deemed useful, that could also be added in some.

    documentation enhancement help wanted good first issue 
    opened by averageflow 0
  • Reset password functionality

    Reset password functionality

    Any user should be able to reset its passwors by means of email. This means we must make Spring Warehouse able to send mail, plugin to send notifications with.

    enhancement 
    opened by averageflow 1
  • Improve test coverage

    Improve test coverage

    More unit and integration tests should be added, and we can extend on the existing unit tests, namely:

    • Integration tests for the controllers
    • Unit tests for the services
    • Unit tests for the controllers

    @Trite8Q1 what do you think of getting the effort started on this?

    help wanted good first issue 
    opened by averageflow 6
Releases(v0.9.1)
  • v0.9.1(Jan 14, 2022)

    First Release Candidate

    • Extensive code cleanup
    • Extensive unit testing implemented
    • Beginning of integration testing implemented
    • Database dump in repo for ease of use
    • Gradle build speed improved and additional functions added
    • Github actions improved
    • Now possible to edit article stocks and to delete users
    Source code(tar.gz)
    Source code(zip)
Owner
Josep Bigorra
Software Engineer, Backend
Josep Bigorra
Spring Boot Login and Registration example with MySQL, JWT, Rest Api - Spring Boot Spring Security Login example

Spring Boot Login example with Spring Security, MySQL and JWT Appropriate Flow for User Login and Registration with JWT Spring Boot Rest Api Architect

null 58 Jan 5, 2023
循序渐进,学习Spring Boot、Spring Boot & Shiro、Spring Batch、Spring Cloud、Spring Cloud Alibaba、Spring Security & Spring Security OAuth2,博客Spring系列源码:https://mrbird.cc

Spring 系列教程 该仓库为个人博客https://mrbird.cc中Spring系列源码,包含Spring Boot、Spring Boot & Shiro、Spring Cloud,Spring Boot & Spring Security & Spring Security OAuth2

mrbird 24.8k Jan 6, 2023
The Quotation Management application is a API REST created using Spring Boot framework.

✅ Quotation Management API - Done ✅ About • Features • Setup • Technologies • Author • License ?? About The Quotation Management application is a API

Vanessa Swerts 6 Apr 29, 2022
Web-based restaurant management system with spring boot and rest API for school final-year project.

Restaurant Management System Developing this for my school as first final year project. It shall be able to handle most of the challanges that encount

Taha Dönük 4 Mar 10, 2022
Spring Boot JdbcTemplate example with SQL Server: CRUD Rest API using Spring Data JDBC, Spring Web MVC

Spring Boot JdbcTemplate example with SQL Server: Build CRUD Rest API Build a Spring Boot CRUD Rest API example that uses Spring Data Jdbc to make CRU

null 7 Dec 20, 2022
A near real time Data Warehouse using the MeshJoin Algorithm

MeshJoin-Data-Warehouse A near real time Data Warehouse using the MeshJoin Algorithm Steps to run the project: Step 1: Run the createDW.sql file -This

M. Adil Fayyaz 2 Dec 1, 2022
A near-real-time Mesh Join Algorithm Implementation provided with a Complete Data warehouse for METRO

Mesh Join Algorithm and Data Warehouse A complete Mesh-Join Algorithm Implementation as provided in the paper R-MESHJOIN . This is demonstrated by the

null 3 Aug 11, 2022
Spring REST API for financial management, developed with Java 11, JWT for authentication, JUnit for unit testing and Oracle Database

control_financial Spring REST API for financial management, developed with Java 11, JWT for authentication, JUnit for unit testing and Oracle Database

Vinicius Cassaro 1 May 27, 2022
Spring JPA Many To Many example with Hibernate and Spring Boot CRUD Rest API - ManyToMany annotation

Spring JPA Many To Many example with Hibernate and Spring Boot CRUD Rest API - ManyToMany annotation

null 17 Dec 28, 2022
See how simple it is to build a REST API with a database using Java and Spring Boot

Seu primeiro projeto Java Web no Spring Boot 2022 Veja como é simples construir uma API REST com banco de dados usando Java e Spring Boot Realização D

DevSuperior 74 Dec 26, 2022
Rate limiting private REST APIs using Java Spring-boot, spring-security and bucket4j

Rate limiting REST APIs using Spring-security filter and Bucket4J Deployed Application (Swagger-ui on heroku) Inspired from: Baeldung Article Applicat

null 20 Jul 18, 2022
Spring Boot REST API authentication best practices using JWT

Spring Boot REST API authentication best practices using JWT Token based API authentication with Spring Security and JWT (JSON web Token) Overview Thi

Prafful Lachhwani 34 Dec 22, 2022
Spring Boot Rest API unit test with Junit 5, Mockito, Maven

Spring Boot Rest API unit testing with Junit 5, Mockito, Maven Apply Spring Boot @WebMvcTest for Rest Controller Unit Test with JUnit 5 and Mockito. F

null 19 Dec 22, 2022
Spring-boot project using open-api, docker, maven, REST

library-service spring-boot project using open-api, docker, maven, REST I used docker to run the project, as well as open-api to generate basic GET an

Sandy Huang 2 Nov 27, 2022
This is simple REST API developed with Spring Boot which allows transactions on taboo cards.

Taboo Cards REST API with Spring Boot Summary: This is simple REST API developed with Spring Boot which allows transactions on taboo cards. Requiremen

Alperen Çubuk 2 Sep 16, 2022
Spring REST service built with Spring initializr and Spring Data.

Spring REST Service Generated with start.spring.io, using Spring Data. Documented using Spring REST Docs. Spring Initializr - Generate new Spring Rest

null 1 Jan 28, 2022
Java, Spring Boot Mini Project - Library Management System - Free Download

Java, Spring Boot Mini Project - Library Management System Local setup Step 1: Download or clone the source code from GitHub to the local machine Step

Sibin Rasiya 15 Dec 27, 2022
Source code of course - Building Real-Time REST APIs with Spring Boot

springboot-blog-rest-api Learn how to build real-time REST APIs with Spring Boot by building a complete Blog App. Source code of Popular Building Real

Ramesh Fadatare 123 Jan 6, 2023
API REST feita 100% em Java com Spring

API REST feita 100% em Java com Spring

M4TH3US17 2 May 8, 2022