DEV Community

suraj kumar
suraj kumar

Posted on

Java Web Services Tutorial: A Beginner’s Guide to Building APIs

Web services have become the backbone of modern applications. From mobile apps to enterprise solutions, almost every system needs to communicate and share data. Java, being one of the most powerful and widely used programming languages, provides strong support for building web services. This tutorial will guide you through the basics of Java web services, explain the different approaches, and provide code examples to help you get started.

What are Web Services?

A web service is a way for two applications to communicate over the internet using standard protocols like HTTP. It allows one application to send a request and another to send back a response, usually in a format like XML or JSON.

In simple terms, a web service is like a messenger that enables different software applications (written in different languages or running on different platforms) to talk to each other.

Types of Web Services in Java

Java supports two main types of web services:

  1. SOAP Web Services (Simple Object Access Protocol):
  • Based on XML messaging.
  • Uses WSDL (Web Services Description Language).
  • Suitable for enterprise-level applications where security and reliability are critical.
  1. RESTful Web Services (Representational State Transfer):
  • Lightweight, simple, and commonly used.
  • Works with standard HTTP methods (GET, POST, PUT, DELETE).
  • Returns data in JSON or XML format.
  • Widely used in modern web and mobile apps.

Setting Up Your Java Web Services Environment

Before creating a web service, you’ll need:

  • JDK (Java Development Kit) – Install the latest version of Java.
  • IDE (Eclipse / IntelliJ / NetBeans) – For easy coding and testing.
  • Apache Tomcat or GlassFish – Application server to deploy services.
  • Maven/Gradle – For dependency management.

Creating a Simple RESTful Web Service in Java

Let’s build a simple RESTful service using JAX-RS (Java API for RESTful Web Services).

Step 1: Add Dependencies (Maven pom.xml)

<dependencies>
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.1</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.35</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.35</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a REST Resource Class

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class HelloService {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello() {
        return "Hello, Welcome to Java Web Services!";
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure web.xml

<web-app>
    <servlet>
        <servlet-name>JerseyServlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.example.services</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>JerseyServlet</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
</web-app>
Enter fullscreen mode Exit fullscreen mode

Step 4: Run and Test

  • Deploy the project on Tomcat/GlassFish.
  • Open browser or use Postman:
http://localhost:8080/yourApp/api/hello
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Welcome to Java Web Services!
Enter fullscreen mode Exit fullscreen mode

Building a REST API with JSON Response

Let’s extend our example to return JSON data.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.json.Json;

@Path("/student")
public class StudentService {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getStudent() {
        return Json.createObjectBuilder()
                .add("id", 101)
                .add("name", "John Doe")
                .add("course", "Java Web Services")
                .build()
                .toString();
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, hitting:

http://localhost:8080/yourApp/api/student
Enter fullscreen mode Exit fullscreen mode

JSON Response:

{
  "id": 101,
  "name": "John Doe",
  "course": "Java Web Services"
}
Enter fullscreen mode Exit fullscreen mode

SOAP Web Service Example in Java

Here’s a quick example using JAX-WS (Java API for XML Web Services).

Step 1: Create the Service

import javax.jws.WebService;
import javax.jws.WebMethod;

@WebService
public class CalculatorService {

    @WebMethod
    public int add(int a, int b) {
        return a + b;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Publish the Service

import javax.xml.ws.Endpoint;

public class CalculatorPublisher {
    public static void main(String[] args) {
        Endpoint.publish("http://localhost:8080/calculator", new CalculatorService());
        System.out.println("Service running at http://localhost:8080/calculator?wsdl");
    }
}
Enter fullscreen mode Exit fullscreen mode

This exposes a SOAP service accessible via WSDL.

REST vs SOAP – Which Should You Choose?

Feature REST Web Service SOAP Web Service
Data Format JSON, XML XML only
Complexity Simple More complex
Performance Fast & lightweight Slower
Security Uses HTTPS, OAuth Built-in WS-Security
Use Case Web, mobile APIs Enterprise-level apps

Choose REST for modern apps.
Choose SOAP for high-security enterprise systems.

Best Practices for Java Web Services

  1. Use proper HTTP methods – GET for fetching, POST for creating, PUT for updating, DELETE for deleting.
  2. Secure your APIs – Use HTTPS, authentication, and authorization.
  3. Use versioning – Example: /api/v1/users.
  4. Handle errors properly – Return meaningful HTTP status codes.
  5. Document your APIs – Use Swagger/OpenAPI for easy understanding.

Conclusion

Java web services provide a powerful way to build scalable and secure APIs. Whether you choose REST for its simplicity or SOAP for enterprise reliability, Java gives you the tools to create professional-grade services.

In this tutorial, you learned:

  • What web services are.
  • Types of web services (REST vs SOAP).
  • How to build a REST API in Java.
  • How to build a SOAP service.
  • Best practices for web service development.  Now you’re ready to start building APIs that power modern applications!

Top comments (0)