我们可以在没有 API ID 的情况下调用外部 API 吗?

Can we call external API without API ID?

我是 API 设计的新手,我正在做一个项目,我需要从 波兰国家银行 调用货币兑换 API http://api.nbp.pl 但我没有看到任何可以找到 API ID 的迹象。如果我尝试 运行 没有 API ID 的应用程序,则此开发在 Spring 启动时会抛出 404 错误。

这是我写的一段代码。

@RequestMapping(method = RequestMethod.GET, value = "/exchangerates/rates/{table}/{code}")
public @ResponseBody Object getAllCurriencyExchangeRates(@PathVariable String table, @PathVariable String code) {

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();

    ResponseEntity<Object> response = 
            restTemplate.getForEntity("http://api.nbp.pl/api/" +table+ "," +code+ Object.class, null, headers);

    return response;
}        

实际查询http://api.nbp.pl/api/exchangerates/rates/a/chf/

那么,我的问题是我们可以在没有 API ID 的情况下调用外部 API 吗?

试试这个 - 我已经测试过 - 它有效。请记住,这只是一个测试实施。 main 方法中的内容必须复制到您的 getAllCurriencyExchangeRates 方法中。 并且肯定会通过变量替换 "a""chf"。我假设 tablecode 是您要使用的变量。我用String是因为我不知道你要return哪种类型的对象。您肯定可以使用自己的 pojo 而不是 String.

package scripts;

import java.net.URI;

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * author: flohall
 * date: 08.12.19
 */
public class Test {

    public static void main(final String[] args){
        final String url = "http://api.nbp.pl/api/exchangerates/rates";
        final URI uri = UriComponentsBuilder.fromHttpUrl(url).path("/").path("a").path("/").path("chf").build().toUri();
        System.out.println(uri);

        final RestOperations restTemplate = new RestTemplate();
        final ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);

        System.out.println(result.getBody());
    }

}

试试这个

ResponseEntity<Object> response =
            restTemplate.getForEntity("http://api.nbp.pl/api/exchangerates/rates/" + table + "/" + code, Object.class, headers);

首先,您试图达到错误 API。这就是为什么您找不到 404 的原因。 404 意味着没有 url 像你打电话一样。

仔细检查你的restTemplate,

restTemplate.getForEntity("http://api.nbp.pl/api/" + table+ "," +code+ Object.class, null, headers);

你在连接字符串时做错了。 它应该看起来像这样;

restTemplate.getForEntity("http://api.nbp.pl/api/exchangerates/rates/"+table+"/"+code, Object.class, null, headers);

对 API 开发人员的提示,首先您应该使用 Postman 玩 api,然后使用 api 编写代码。