RESTful 的核心是把一切抽象为资源,用 URL 表达资源位置,用 HTTP 动词表达操作:GET 查、POST 增、PUT/PATCH 改、DELETE 删。约定包括路径用名词复数、状态码语义化(200 成功、201 创建、400 参数错误、401 未认证、403 无权限、404 不存在、500 服务端错误),版本号放路径或头部。
面试答完规范后,常被追问 RESTful 的不足:接口粒度难以匹配前端页面,一个详情页可能要请求多个接口,于是 GraphQL 与 BFF 中间层出现。回答时说明实践中不必教条,批量场景可以设计复合接口,但统一规范、语义化错误码与接口文档是协作的底线。
// RESTful 风格调用示例:动词表达操作,路径表达资源 const api = 'https://api.example.com'; const list = () => fetch(api + '/articles?page=1&size=20'); const item = id => fetch(api + '/articles/' + id); const create = body => fetch(api + '/articles', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const update = (id, body) => fetch(api + '/articles/' + id, { method: 'PUT', body: JSON.stringify(body) }); const remove = id => fetch(api + '/articles/' + id, { method: 'DELETE' }); console.log('GET 查、POST 增、PUT 改、DELETE 删,路径统一用名词复数');