在Debian上使用Swagger(现称为OpenAPI)可以极大地提高前后端开发的效率和协作性。以下是在Debian上使用Swagger的一些最佳实践:
sudo apt update
sudo apt install openjdk-11-jdk
sudo apt install maven
springfox-boot-starter
。pom.xml
文件中添加Swagger依赖:<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
application.yml
或application.properties
文件中配置Swagger:springfox:
documentation:
swagger-ui:
enabled: true
mvn spring-boot:run
http://localhost:8080/swagger-ui/
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
@Api(tags = "Sample API")
public class SampleController {
@GetMapping("/hello")
@ApiOperation(value = "Say hello", response = String.class)
public String sayHello() {
return "Hello, World!";
}
@PostMapping("/data")
@ApiOperation(value = "Send data", requestBody = @io.swagger.annotations.ApiRequestBody(content = @io.swagger.annotations.ApiContent(schema = @io.swagger.annotations.ApiSchema(implementation = String.class))), response = String.class)
public String sendData(@RequestBody String data) {
return "Received: " + data;
}
}
如果你想要通过HTTPS访问Swagger UI或者想要更好地控制访问,你可以使用Nginx作为反向代理。
sudo apt install nginx
配置Nginx以将流量转发到你的Node.js应用程序。编辑Nginx配置文件(通常位于/etc/nginx/sites-available/default
),添加以下内容:
server {
listen 80;
server_name your_domain_or_ip;
location /api-docs {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host host;
proxy_cache_bypass http_upgrade;
}
}
保存文件并重启Nginx:
sudo systemctl restart nginx
现在,你应该可以通过http://your_domain_or_ip/api-docs
访问Swagger UI。