← Volver

API Rest sencilla en Spring Boot

Publicado el 28 de enero de 2026

Dentro de nuestro proyecto creamos el paquete «controller» y dentro de él, la clase SaludoController.java

SaludoController.java tendrá el siguiente código:

package com.ccorreas.primeraApi.controller;

import com.ccorreas.primeraApi.dto.SaludoResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/apisaludos")
public class SaludoController {

    @GetMapping("/hola")
    public String holaMundo(){
        return "Hola Mundo";
    }

    @GetMapping("/holanombre/{nombre}/{edad}")
    public String holaMundoNombre(@PathVariable String nombre, @PathVariable int edad){
        return "Hola mundo! " + nombre + " Tu edad es: " + edad;
    }

    @GetMapping("/holanombrejson/{nombre}/{edad}")
    public SaludoResponse holaMundoNombreJSON(@PathVariable String nombre, @PathVariable int edad){
        return new SaludoResponse("Hola mundo!", nombre, edad);
    }

}

Y la clase SaludoResponse.java este código:

package com.ccorreas.primeraApi.dto;

public class SaludoResponse {
    private String mensaje;
    private String nombre;
    private int edad;

    public SaludoResponse(String mensaje, String nombre, int edad) {
        this.mensaje = mensaje;
        this.nombre = nombre;
        this.edad = edad;
    }

    public String getMensaje() {
        return mensaje;
    }

    public String getNombre() {
        return nombre;
    }

    public int getEdad() {
        return edad;
    }
}