DEV Community

Cover image for 🚀 Demystifying APIs and REST with Spring Boot: Crafting Product Services Made Easy🚀
Abhiram
Abhiram

Posted on

🚀 Demystifying APIs and REST with Spring Boot: Crafting Product Services Made Easy🚀

What is API

API stands for Application Programming Interface. How can we understand API from full form ? Let us simpliy this. We can say it is an interface for an application. Till now we might have created interface for a class. We might have implemented this interface.

Interface Runnable {
Void run();
}

Any class implemented this interface has to implement run method in it. We can say it is a contract between class and interface ,that whichever class implements this, has to implement this method in it.

Basically when we create a interface it is like we are creating a contract that whichever class implements this interface has to follow a certain structure ,i.e. it has to implement all the methods or else we will get compilation error.

Similarly API is also a contract. If any service wants to connect to our API be it front end, third party, anything, it has to follow a certain structure that we created for API. Contract in API is what we will accept in API and what we will return from API.

*Major things we will follow in API are *

- HTTP methods

HTTP stands for Hyper Text transfer protocol. But why we are not discussing HTTPS. Difference between HTTP and HTTPS is protocol. In HTTPS the data will be in encrypted format, in between client and server ,it will not be readable.

HTTP or HTTPS is used ,how to transfer the text, how to send it in optimized manner. As transfer is happening between two systems we can say two operating systems over network, so we should be having knoweldge about which data structure to use to send the data in optimized way and also about networking and operating systems.

HTTP methods shows us ,what operations we can use to interact with server.

Image description

In postman we can see all the HTTP methods, they are basically different methods that we can use to interact with server

- Endpoint URL

It means ,the URL that our API will be executing. For example we want to create products it will be like www.domain.com, this will be the domain and for creating products it will be www.domain.com/createProducts. createProducts is API end point.

- Request

-> It is input what we send

- Response

-> It is output what we get from API

For example ,I am running an e-commerce website and I want to use services from razorpay for payment gateway. So for this to happen, the e-commerce websit has to send the order details to razorpay for the transaction to happen, how do we send the data to razorpay ?

Image description

In the above you can see

  • HTTP method is post to create order
  • End point URL is /orders.
  • Right side of the image, you can -d which is the request we are sending for example money, currency type etc
  • Response we will get like in the below image.

Image description

When two applications are talking to each other, they must have well defined API contract.

Above all forms the API contract, which means

  • what is operation we are doing
  • what is the end point URL
  • what type of information we have to send in request
  • what response we can except from API

Concluding API is set of functionalities or methods that are provided by other system for us to use.

- What is REST ?

REST stands for Representation State Transfer. It means that every call we make to API, there should be a transfer of state.

For example in first call I will call the API for all the products and In the second call I will call the API for a particular product., now in the second call all the details will be sent again. The authorization etc will happen again in the second call also.

Every call we make to the backend ,it will be a new call. It may be the same API or different API, it will become a new call. No state will be remembered. Whether we will call the same API 10 times or different API it will be a new call and the previous call state will not be remembered.

But why do we need to send the data again and again to server ? It reduces the task for server i.e. the server will not remember all the client details, the client has to provide the details to the server again and again.

There will be thousands of customers making thousands of calls, if the server has to remember all the details of the users and their call, it will be a huge dataset at server side.

  • REST helped to make server less complex and it helped in reducing the development time.

  • Whenever you see a name REST API’s ,it means API’S are built using REST concept.

- API Hands-On

Let us build API’s related to product service. Let us create two models, one for product and one for category. one product will have one category but one category can have multiple products that means 1: 1 relationship between product and category and many : 1 relationship between category and product.

So let product model contains
• Productid
• Title
• Price
• Description
• Image
• cateogoryID

and let category contains
• id
• title
• description

Now we will build the API’s in controller layer, the controller layer calls service layer and service layer calls repository and repository calls Database, for database we will create models.

So first we will create Database, from Database we will create models, then we will create repositories and then service layer and in controller we will create the API i e (END POINT URL).

But right now what we will do is instead of creating Database we will call third party product API’s in service layer. So the data flow will be like

- Request will be like

  • Client -> API (Controller END POINT URL) -> Service layer -> Third party API **

- Response will be like**

  • Third party API -> Service layer -> Controller -> Client

We will use this https://fakestoreapi.com/docs third party service which provides API for this demo

Since we are not using Database do we still need models ? Yes because from API what ever data we return we will send it in models, from models we will create DTO (Data transfer object). So we will always build models even if we call third party or even if we have database.

What is DTO ?

Suppose we have a User model in which we have
• UserId
• Email
• Password
• Address

And we are returning User model data to frontend from API, now we are sending confidential data to frontend. This data can be hacked through browser, so to filter out data and send what is necessary we use DTO

In DTO we will be having
• UserId
• Email
• Addrress

From DTO we do

  • Hide confidential data
  • Reduce pay load size (response)
  • Maintains separation between model and actual data we send as response

So first we will code

  • Models
  • DTO’s
  • Controller with dummy API
  • Service layer calling third party API as well as Database.

Image description

In https://start.spring.io/ we will setup the Spring Boot project in a easy manner. I have filled the project data and I have added dependencies such as spring web with which we can REST API’s using spring MVC and Lombok for using getters and setters.

Image description

In the above picture ,I have imported the project in intellij IDE and I have created the packages for model, dto, service, controller.

Now we will go to fakestore and by seeing it’s entities and attributes in those entities, we will create our own models.

Image description

Output is can be seen below

Image description

Below we can see the attributes of products.

Image description

I have created product model and I have created attributes as per the products attributes in fakestore api. Make sure that attributes names matches with attributes in fakestore attributes.

Image description

Here we can see the categories reposnse for get all categories.

We created two DTO’s for the products model. ProductRequestDTO is for incoming data (client request) and ProductResponseDTO is for output data that we send it back to client from REST API.

Image description

Here we are adding all the attributes of product model including id as it may help in front-end.

Image description

We will use @RestController Annotation for Controller. In Spring Boot, a web application can have many end point URL’s (API’s) that clients can use and these are handled by controller’s. Now @RestController annotation is designed specifically for building RESTful API’s

**

If we simplify this

**

• A controller is the one which decides where each request should go.
• RESTful means that the web service follows a set of principles that make it easy to work with. In the context of Spring Boot, it often means that the service can provide and receive data in a format like JSON or XML and follows certain conventions for how URLs should look.
• @RestController: When a class is marked with @RestController, it's like saying, this class is a special type of controller, and it's specifically designed to handle requests and responses for RESTful web services.
• @GetMapping, @PostMapping, etc.: Inside a @RestController, we often see methods annotated with things like @GetMapping, @PostMapping, etc. These annotations specify which URLs (endpoints) the methods should handle and what type of HTTP request (GET, POST, etc.)

Let us create one dummy REST API in the REST controller which will create two products and return it and we will call this REST API to see if API is getting invoked or not.

Image description

Here we have created two ProductResponseDTO and we are returning this two as a list from the API.
To set the data to ProductResponseDTO object we have used getters and setters, for that we have used Lombok dependency which will automatically create getters and setters if we use @Getters and @Setters annotations

Image description

Image description

In above image we can see response is returned as ResponseEntity. In simple words ResponseEntity is like a bucket which will hold our response and in addition we can add the status of the response. Above we can I have put the status as ok and we are sending the response.

Inside ResponseEntity we can see, the response can be anything and we can the status also.
Now I will run the SpringBoot application and we will test the API in postman.

Image description

Image description

Crucial points

  • How the request reached from postman / client to Spring Boot server or tomcat server
  • How the request reached the correct controller and how the response was sent back correctly

In the next blog we will cover the above points.

Top comments (0)