使用Spring Boot创建Rest API

1 简介

在这篇文章中,我们通过使用Spring Boot和Spring Initializr来演示创建简单的RESTful API的过程。Spring Boot是一个流行的框架,它简化了Spring应用程序的开发和部署,而Spring Initializr是一个基于Web的服务,它可以根据你的要求生成项目模板。

下面是关于如何使用Spring Boot和Spring Initializr创建RESTful API的分步骤指南:

2 使用Spring Initializr设置项目

进入Spring Initializr网站,填写以下内容:

  • 项目类型:Maven项目
  • 语言:Java
  • 包装:Jar
  • Java 版本:11
  • 组:com.example
  • 神器:restful-api
  • 命名:restful-api
  • 描述:使用Spring Boot的简单RESTful API
  • 包装名称:com.example.restfulapi

在 "选项 "下,选择以下:

  • 网络:Spring Web
  • 开发工具:Spring Boot DevTools (可选,用于开发目的)

点击 "生成",将项目模板下载为ZIP文件。提取文件并将项目导入你喜欢的IDE。

3 创建模型类

在com.example.restfulapi.model包中创建一个名为Person的新Java类。这个类在我们的RESTful API中代表一个人。

package com.example.restfulapi.model;

public class Person {
    private Long id;
    private String firstName;
    private String lastName;

    // 构造函数、获取器和设置器
}

4 创建控制器类

在com.example.restfulapi.controller包中创建一个名为PersonController的新Java类。这个类将为我们的RESTful API处理HTTP请求。

package com.example.restfulapi.controller;

import com.example.restfulapi.model.Person;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/api/v1/people")
public class PersonController {

    private final List<Person> people = new ArrayList<>();
    private final AtomicLong counter = new AtomicLong();

    @GetMapping
    public List<Person> getAllPeople() {
        return people;
    }

    @PostMapping
    public Person createPerson(@RequestBody Person person) {
        person.setId(counter.incrementAndGet());
        people.add(person);
        return person;
    }

    @GetMapping("/{id}")
    public Person getPersonById(@PathVariable("id") Long id) {
        return people.stream()
                .filter(person -> person.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    @PutMapping("/{id}")
    public Person updatePerson(@PathVariable("id") Long id, @RequestBody Person updatedPerson) {
        Person person = getPersonById(id);
        if (person != null) {
            person.setFirstName(updatedPerson.getFirstName());
            person.setLastName(updatedPerson.getLastName());
        }
        return person;
    }

    @DeleteMapping("/{id}")
    public void deletePerson(@PathVariable("id") Long id) {
        people.removeIf(person -> person.getId().equals(id));
    }
}

5 运行应用程序

在你的IDE中运行RestfulApiApplication类,或者在项目根目录下使用以下命令:

./mvnw spring-boot:run

6 测试API

你可以使用Postman或curl等工具来测试API。这里有一些样本请求:

  • 获取所有的人:GET http://localhost:8080/api/v1/people
  • 创建一个新的人:POST http://localhost:8080/api/v1/people 与JSON主体 {"firstName":"John", "lastName":"Doe"}
  • 通过身份证找一个人:GET http://localhost:8080/api/v1/people/1
  • 更新一个人:PUT http://localhost:8080/api/v1/people/1 与JSON主体 {"firstName": "Jane", "lastName": "Doe"}
  • 删除一个人:DELETE http://localhost:8080/api/v1/people/1

7 总结

在这篇文章中,我们学习到了使用Spring Boot和Spring Initializr创建一个简单的RESTful API的过程。我们创建了模型类来代表一个人,实现了控制器来处理HTTP请求,并使用样本请求测试了API。Spring Boot和Spring Initializr让我们能很容易地构建RESTful API和其他类型的应用程序,你的下个项目可以尝试使用它们!

THE END