使用Spring Boot创建Rest API

开发 前端
在这篇文章中,我们学习到了使用Spring Boot和Spring Initializr创建一个简单的RESTful API的过程。我们创建了模型类来代表一个人,实现了控制器来处理HTTP请求,并使用样本请求测试了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和其他类型的应用程序,你的下个项目可以尝试使用它们!

责任编辑:武晓燕 来源: Java学研大本营
相关推荐

2023-07-17 18:42:47

gRPCDemo项目

2020-10-18 08:51:18

Spring Boot

2014-01-07 14:39:26

Android开发RxJavaREST

2023-08-14 09:00:00

APIgRPCREST

2020-07-07 07:00:00

Spring WebFREST APIReactive AP

2012-02-16 11:32:18

ibmdw

2012-02-24 15:28:33

ibmdw

2021-12-02 16:20:18

RabbitMQAPIRest

2024-01-18 07:53:37

2022-01-07 15:11:27

项目Go 框架

2017-04-25 10:46:57

Spring BootRESRful API权限

2024-02-22 18:12:18

微服务架构设计模式

2013-10-14 09:29:20

RESTJSONJava

2021-08-20 09:00:00

Node.js开发API

2022-06-21 09:27:01

PythonFlaskREST API

2023-04-18 15:18:10

2023-10-06 23:40:49

Spring开发

2023-11-19 20:16:43

RESTAPIPOST

2022-05-31 07:40:41

ArctypeFeather.jsSQLite

2021-11-04 09:00:00

JavaSpring BootURL
点赞
收藏

51CTO技术栈公众号