在拉动外部api用于rails后端时遇到了麻烦。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在拉动外部api用于rails后端时遇到了麻烦。相关的知识,希望对你有一定的参考价值。

所以,首先,这是我使用的api。

https:/fdc.nal.usda.govapi-guide.html

我的目标是提取信息用于健康应用程序,以便用户可以跟踪他们的食物消费。我是个新手,在将数据拉入后台时遇到了麻烦。这是我的seeds.rb文件

API_HOST = "https://api.nal.usda.gov/"
LIST_PATH = "fdc/v1/foods/list"

  def self.list
    url = "#{API_HOST}#{LIST_PATH}"
    params = {
      dataType: "Branded",
      pageSize: 100,
      sortBy: "asc"
    }

    response = HTTP.auth("Bearer #{ENV['API_KEY']}").get(url, params: params)
    response.parse
  end

  self.list["foods"].each do |food|
    Food.get_foods_list(food)
end

在我的食物模型中。

class Food < ApplicationRecord


  def  self.get_foods_list(food)
    self.create(
        name: food["description"] ,
        protein: food["foodNutrients"]["nutrientName"]["protein"]["value"],
        carbohydrates:  food["foodNutrients"]["nutrientName"]["carbohydrate, by difference"]["value"],
        fats: food["foodNutrients"]["nutrientName"]["Total lipid (fat)"]["value"]
    )
  end
end

当我试图用api数据在数据库中播种时

NameError: uninitialized constant HTTP

当我试图用api数据播种我的数据库的时候.

我觉得我好像漏掉了一些小东西,但我不知道是什么。

这是我试图拉取的数据的一个例子。

foods: [
{
fdcId: 470794,
description: "CHEDDAR CHEESE",
dataType: "Branded",
gtinUpc: "025555300085",
publishedDate: "2019-04-01",
brandOwner: "Coblentz Distributing, Inc.",
ingredients: "PASTEURIZED MILK, CHEESE CULTURE, SALT, ENZYMES AND ANNATTO (VEGETABLE COLOR).",
foodNutrients: [
{
nutrientId: 1005,
nutrientName: "Carbohydrate, by difference",
nutrientNumber: "205",
unitName: "G",
derivationCode: "LCCD",
derivationDescription: "Calculated from a daily value percentage per serving size measure",
value: 0,
},
{
nutrientId: 1079,
nutrientName: "Fiber, total dietary",
nutrientNumber: "291",
unitName: "G",
derivationCode: "LCCD",
derivationDescription: "Calculated from a daily value percentage per serving size measure",
value: 0,
},
{
nutrientId: 1087,
nutrientName: "Calcium, Ca",
nutrientNumber: "301",
unitName: "MG",
derivationCode: "LCCD",
derivationDescription: "Calculated from a daily value percentage per serving size measure",
value: 735,
},
{
nutrientId: 1089,
nutrientName: "Iron, Fe",
nutrientNumber: "303",
unitName: "MG",
derivationCode: "LCCD",
derivationDescription: "Calculated from a daily value percentage per serving size measure",
value: 0,
},
{
nutrientId: 1104,
nutrientName: "Vitamin A, IU",
nutrientNumber: "318",
unitName: "IU",
derivationCode: "LCCD",
derivationDescription: "Calculated from a daily value percentage per serving size measure",
value: 882,
},
{
nutrientId: 1162,
nutrientName: "Vitamin C, total ascorbic acid",
nutrientNumber: "401",
unitName: "MG",
derivationCode: "LCCD",
derivationDescription: "Calculated from a daily value percentage per serving size measure",
value: 0,
},
{
nutrientId: 1003,
nutrientName: "Protein",
nutrientNumber: "203",
unitName: "G",
derivationCode: "LCCS",
derivationDescription: "Calculated from value per serving size measure",
value: 23.53,
},
{
nutrientId: 1004,
nutrientName: "Total lipid (fat)",
nutrientNumber: "204",
unitName: "G",
derivationCode: "LCCS",
derivationDescription: "Calculated from value per serving size measure",
value: 32.35,
},
{
nutrientId: 1008,
nutrientName: "Energy",
nutrientNumber: "208",
unitName: "KCAL",
derivationCode: "LCCS",
derivationDescription: "Calculated from value per serving size measure",
value: 412,
},
{
nutrientId: 2000,
nutrientName: "Sugars, total including NLEA",
nutrientNumber: "269",
unitName: "G",
derivationCode: "LCCS",
derivationDescription: "Calculated from value per serving size measure",
value: 0,
},
{
nutrientId: 1093,
nutrientName: "Sodium, Na",
nutrientNumber: "307",
unitName: "MG",
derivationCode: "LCCS",
derivationDescription: "Calculated from value per serving size measure",
value: 618,
},
{
nutrientId: 1253,
nutrientName: "Cholesterol",
nutrientNumber: "601",
unitName: "MG",
derivationCode: "LCCS",
derivationDescription: "Calculated from value per serving size measure",
value: 103,
},
{
nutrientId: 1257,
nutrientName: "Fatty acids, total trans",
nutrientNumber: "605",
unitName: "G",
derivationCode: "LCCS",
derivationDescription: "Calculated from value per serving size measure",
value: 0,
},
{
nutrientId: 1258,
nutrientName: "Fatty acids, total saturated",
nutrientNumber: "606",
unitName: "G",
derivationCode: "LCCS",
derivationDescription: "Calculated from value per serving size measure",
value: 20.59,
},
],
allHighlightFields: "<b>Ingredients</b>: PASTEURIZED MILK, <em>CHEESE</em> CULTURE, SALT, ENZYMES AND ANNATTO (VEGETABLE COLOR).",
score: 542.84247,
答案

你应该使用HTTParty gem进行外部api调用。这里是链接到创业板 https:/github.comjnunemakerhttparty。

这是你需要的一个想法

class FetchAPI
  include HTTParty
  base_uri "https://api.nal.usda.gov"

  def self.list
    params = {
      dataType: "Branded",
      pageSize: 100,
      sortBy: "asc"
    }

    response = self.class.get("/fdc/v1/foods/list", { headers: "Bearer #{ENV['API_KEY']}"}, query: params)
    response.parse
  end

end

FetchAPI.list["foods"].each do |food|
  Food.get_foods_list(food)
end

以上是关于在拉动外部api用于rails后端时遇到了麻烦。的主要内容,如果未能解决你的问题,请参考以下文章

Rails 应用程序 HTTP 到 HTTPS 重定向不适用于公开的 API

无法解释无效的 CSRF 令牌 rails api

使用 React 前端处理受密钥保护的 API 操作的正确方法是啥?

ReactJS Axios 外部 API CORS

使用 chrome 浏览器登录后端时 Magento 显示错误

从 Heroku Angular 前端调用 Heroku springboot 后端时,Rest 调用返回 403