"I'm studying Java, but I don't understand what goes on behind the scenes of web applications."
"APIs seem difficult... but I want to learn how to use them."
For those who have such concerns,Experience creating a REST API server in Javais recommended.
Starting with the basics of APIs,Receiving requests, JSON responses, and POST/GET processingto
By experiencing the entire process, you will be able to quickly deepen your practical skills and understanding of Java.
In this article, we will introduce how to build a system that even beginners can use.Simple REST API serverHow to make
Easy to understand, detailed, and with codeLet me explain.
- What is a REST API Server?
- Understand the features and configuration you need
- Standard Java classes to use
- Implementation: Creating a REST API server in Java
- Common errors and solutions
- Application: File saving and JSON format support
- Complete code summary and configuration
- Summary: Understanding the basics of APIs in Java
What is a REST API Server?
It is the gateway between the server and the client.
Bottom line: REST APIs are a gateway for connecting apps and web services together.
For example, when getting today's weather forecast using a weather app,
Behind the scenes, the following interaction takes place: "Access the API → The server returns data in JSON format."
You can also implement this mechanism in Java code.
The Ministry of Education, Culture, Sports, Science and Technology also promotes "development of information utilization skills"Understanding the structure and mechanisms of information and communicationsWe place great importance on the following.
(Source: https://www.mext.go.jp/a_menu/shotou/zyouhou/detail/1375607.htm)
Understand the features and configuration you need
You can create a REST API with just two functions
Conclusion: The basic API is complete just by implementing GET and POST operations.
The API we will create will look something like this:
GET /message
→ Return a list of messagesPOST /message
Receive and save messages
The setup is very simple:
JavaHttpServer.java
:API invocation and routing process/message
→ GET/POST compatible- Data is stored in a simple List (in-memory processing)
Standard Java classes to use
You can create an API without additional libraries
Java hascom.sun.net.httpserver.HttpServer
There is a standard class.
If you use this,No server software such as TomcatYou can create an API server.
Required imports:
import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpExchange;
Implementation: Creating a REST API server in Java
import com.sun.net.httpserver.*; import java.io.*; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.*; public class JavaHttpServer { private static final List messages = new ArrayList<>(); public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/message", new MessageHandler()); server.setExecutor(null); // Default thread System.out.println("API server running: http://localhost:8000/message"); server.start(); } static class MessageHandler implements HttpHandler { @Override public void handle(HttpExchange exchange) throws IOException { String method = exchange.getRequestMethod(); if ("GET".equalsIgnoreCase(method)) { handleGet(exchange); } else if ("POST".equalsIgnoreCase(method)) { handlePost(exchange); } else { exchange.sendResponseHeaders(405, -1); // Method not allowed } } private void handleGet(HttpExchange exchange) throws IOException { String response = String.join("\n", messages); byte[] bytes = response.getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(200, bytes.length); try (OutputStream os = exchange.getResponseBody()) { os.write(bytes); } } private void handlePost(HttpExchange exchange) throws IOException { InputStream is = exchange.getRequestBody(); String body = new String(is.readAllBytes(), StandardCharsets.UTF_8); messages.add(body); String response = "Message accepted."; byte[] bytes = response.getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(200, bytes.length); try (OutputStream os = exchange.getResponseBody()) { os.write(bytes); } } } }
Common errors and solutions
Resolves common stumbling points
Error 1: Port is in use → Port 8000 may be in use by another app.
- Solution:
8001
Change to another port number such as
Error 2: com.sun.net.httpserver not found
- Solution: It is included as standard in the JDK.
JDK 11 and later
Since it may not exist inRuns on JDK 8-10OrJetty
Switch to a different server.
Application: File saving and JSON format support
Towards a more practical API
- Save submitted data to a file or database
- Convert the response to JSON (using the Jackson library, etc.)
PUT
orDELETE
Support for HTTP methods such as
Complete code summary and configuration
JavaHttpServer.java
: Completed in one file- port:
8000
- Endpoints:
/message
- HTTP method:
GET
,POST
Summary: Understanding the basics of APIs in Java
In this article,How to build a REST API server in JavaWe introduced the following.
What you will learn in this article:
- How to start a Web API server in Java
- How to write GET and POST operations
- How to avoid stumbling points
FirstThe feeling that "APIs are actually easy"is the first step.
Please try modifying your own API and deepen your learning!