如何基于OpenAPI 3.0实现POST接口返回lon与lat求和结果?
Got it, let's walk through this step by step. You've already got the base OpenAPI 3.0 spec for a /coordinates POST endpoint that takes lon and lat as numeric parameters. To return their sum, you'll need to update two key parts: your OpenAPI definition to document the response structure, and your backend code to handle the calculation.
1. Update the OpenAPI 3.0 Definition First
First, let's refine your spec to clearly define what the response will look like—this makes your API predictable for consumers and compatible with tools like code generators. We'll add a structured response with a sum field (you could also return the raw numeric sum if that fits your use case, but an object is more flexible for future changes).
Here's the updated spec:
openapi: 3.0.0 info: version: '1.0.0' title: Coordinate Sum API description: Accepts longitude and latitude values, returns their calculated sum paths: /coordinates: post: responses: '201': description: Sum calculated successfully content: application/json: schema: type: object properties: sum: type: number format: double description: The sum of the provided longitude (lon) and latitude (lat) '400': description: Invalid input (missing or non-numeric coordinates) requestBody: required: true content: application/json: schema: type: object properties: lon: type: number format: double lat: type: number format: double required: [lon, lat] # Enforce clients send both values
I added a few key improvements here:
- A
contentsection under the 201 response to define the returned JSON structure - A 400 error response to document invalid input scenarios
- Marked
lonandlatas required in the request schema (good practice to avoid missing values)
2. Implement the Backend Calculation Logic
Next, you need to add the sum calculation in your backend code. Below are examples for two common frameworks to cover different tech stacks:
Example 1: Node.js with Express
const express = require('express'); const app = express(); app.use(express.json()); // Parse JSON request bodies app.post('/coordinates', (req, res) => { const { lon, lat } = req.body; // Basic validation to catch bad input if (typeof lon !== 'number' || typeof lat !== 'number') { return res.status(400).json({ error: 'lon and lat must be valid numbers' }); } const sum = lon + lat; res.status(201).json({ sum }); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
Example 2: Java with Spring Boot
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; // DTO for incoming request class CoordinateRequest { private Double lon; private Double lat; // Getters and setters public Double getLon() { return lon; } public void setLon(Double lon) { this.lon = lon; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } } // DTO for outgoing response class CoordinateSumResponse { private Double sum; public CoordinateSumResponse(Double sum) { this.sum = sum; } public Double getSum() { return sum; } } @RestController public class CoordinateController { @PostMapping("/coordinates") public ResponseEntity<CoordinateSumResponse> calculateSum(@RequestBody CoordinateRequest request) { // Add validation here if using Spring's @Valid annotation if (request.getLon() == null || request.getLat() == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } Double sum = request.getLon() + request.getLat(); return new ResponseEntity<>(new CoordinateSumResponse(sum), HttpStatus.CREATED); } }
Both examples follow the same core workflow:
- Parse the
lonandlatvalues from the incoming request body - Validate that both values are present and numeric (to avoid runtime errors)
- Calculate their sum
- Return the sum in the response with a 201 Created status code
内容的提问来源于stack exchange,提问作者AlexM88

