Code Chefs
Guide

How REST APIs Work and How to Build One in Java

Learn how REST APIs use HTTP methods, URIs, and JSON. See how to call an API and build a Java service with Spring or JAX-RS.

Codechefs Insights 5 min read
How Do REST APIs Work? Calling and Building Them in Java

What Is a REST API?

A REST API lets software exchange data through rules based on Representational State Transfer, or REST. A client sends an HTTP request to a server. The server processes it and returns a response, often as JSON.

Think of a store app that needs details about one item. It sends a request to a resource URI, such as /products/42. The server returns that product's data, including its name and price.

REST describes how parts of a system should interact. It does not require one programming language or framework. A Java service can serve a web app, phone app, or another service.

Laptop and network device arranged on a bright desk for software development
A simple setup for API work

How REST Architecture Works

REST uses a client-server model. The client handles the user-facing task, while the server stores or works with data. They communicate through HTTP, so each side can change without rebuilding the other.

Each resource needs a unique identifier, usually a URI. For example, /products can name a collection, while /products/42 points to one item. The URI identifies the resource, not a screen or a specific action.

HTTP methods show what the client wants to do. GET reads data, POST creates data, PUT replaces data, and DELETE removes data. Responses often use JSON because many languages can parse it with common tools.

REST also sets constraints, including statelessness and a uniform interface. With statelessness, each request carries the details needed to handle it. The server does not rely on memory of earlier requests from that client. This can reduce server work and makes it easier to spread requests across servers.

  • GET: Read a resource, such as a product.
  • POST: Send data to create a new resource.
  • PUT: Replace a resource at a known URI.
  • DELETE: Remove a resource.

The MDN overview of HTTP methods explains how common methods shape requests. For a broader view of REST, see the REST chapter in Roy Fielding's dissertation.

Network devices and cables arranged to suggest connected REST services
A quiet view of connected systems

How to Call a REST API

To call a REST API, choose the resource URI and the HTTP method that matches your task. Then send the request with any needed headers and data. A tool such as curl, an API client, or your app can make the call.

For example, a GET request to https://api.example.com/products/42 asks for one product. The server may return a JSON response with an ID, name, and price. A POST request to /products can send a JSON body with the fields for a new product.

Check the response status as well as its body. A 200 status often means the request worked. A 201 commonly means a resource was created, while a 404 means the server could not find it. A 401 or 403 often points to an access problem.

Many APIs require authentication. An API key may go in a request header. Basic authentication sends a user name and password in encoded form, so use it only over HTTPS. Bearer token authentication sends a short-lived access token, often in the Authorization header.

  1. Read the API docs and find the URI, method, and required fields.
  2. Set the right headers, including the content type when sending JSON.
  3. Add the required API key or token without exposing it in public code.
  4. Send the request, then check its status and response data.

Calling a REST API from Java

Java offers several ways to send HTTP requests. The built-in HttpClient works well for many apps and avoids an extra library. Create a client, build a request, send it, and read the response body.

For a GET call, set the URI to the product endpoint and choose the GET method. Send the request with the client, then check the status code before parsing the JSON body. A JSON library can map that body to a Java class.

For a POST call, create a request body with the new product fields. Set the content type to application/json and send the body with the request. Keep secrets, such as API keys, in secure settings rather than source code.

Handle errors and timeouts as part of the call. A server may be down, return an error, or take too long to reply. Use a safe retry only when the request can be repeated without creating unwanted duplicate data.

Laptop and blank notebook on a clean desk for Java API development
A focused workspace for Java development

How to Implement a REST API in Java

To implement a REST API in Java, choose a framework and define the resources your service will expose. Spring and JAX-RS are common choices. Spring uses annotations to map Java methods to routes and HTTP methods.

For example, a product service might expose /products and /products/{id}. A GET route can list products or return one product. A POST route can accept a JSON body and create a new product. A PUT route can update one, and DELETE can remove it.

Keep the route layer focused on HTTP input and output. Put business rules in a service layer, and let a data layer handle storage. Return clear status codes and JSON that clients can use. Validate incoming fields before saving them.

Start with a small set of routes, then test each one with valid and invalid input. Add authentication if the data or actions need protection. An OpenAPI document can describe routes, fields, and status codes for other developers.

REST API Best Practices and Benefits

Use nouns for resource paths, such as /orders, rather than action names. Keep paths consistent, and use HTTP methods to show the action. Return status codes that match the result, and give clients useful error details without exposing private data.

Use HTTPS for requests, and protect tokens and API keys. Validate input on the server, set sensible timeouts, and limit access where needed. Version an API when a change would break existing clients. These steps make updates safer.

REST's uniform interface helps teams build clients and services with clear boundaries. Stateless requests can make scaling simpler because any suitable server can handle a call. JSON is widely supported, so apps in different languages can share data.

REST APIs also fit well in microservices, where small services share data through defined routes. Yet REST is not the right choice for every task. Large data transfers or real-time streams may call for another design. Choose it when resource-based requests over HTTP fit the job.

Frequently asked questions

How does a REST API work?
A client sends an HTTP request to a resource URI, and the server returns a response. The request uses a method such as GET or POST, and the response often contains JSON.
How do I call a REST API?
Find the API's URI, method, and required headers in its documentation. Send the request, include any needed authentication, then check the status code and response body.
How do I call a REST API from Java?
Use Java's built-in HttpClient to create and send an HTTP request. Check the response status, then parse the JSON body with a JSON library.
How do I implement a REST API in Java?
Choose a framework such as Spring or JAX-RS, then map resource routes to Java methods. Add input checks, suitable status codes, and JSON responses.
Why is statelessness important in REST?
Each request includes the information needed for the server to handle it. This reduces reliance on stored client state and can make it easier to share requests across servers.
rest api basicshttp request methodsjson api responsejava http clientspring rest api
Share XFacebookWhatsAppTelegram

Related reading