FatSecret Food Database REST API Client with Typescript

9 Min Read

Have you ever ever puzzled, find out how to present your product a wealthy meals and meals database? After we determined to have meals search performance in certainly one of our merchandise, Suguard (diabetes diary app, below growth in React Native with Firebase and Typescript), we had to do a little analysis on what service would swimsuit our wants finest. We wanted one thing that’s free for essentially the most fundamental functionalities to validate our product with customers. After some analysis, we realized, that FatSecret could be the only option if we need to use 100% free service (essentially the most fundamental pricing tier) for now. It won’t swimsuit all of your wants, however we by no means declare that it’s the finest service of all. Some info about FatSecret from their homepage:

The #1 meals and diet database on the earth, utilized by greater than 10,000 builders, in additional than 50 international locations contributing in extra of 500 million API calls each month.

Authentication

To make use of FatSecret API it’s good to register as a developer right here. The API makes use of authentication based mostly on OAuth Core 1.0 protocol for securely signing all requests. Though documentation on FatSecret’s web page seems to be wealthy, it takes a while to undergo it. Right here’s why this tutorial article comes by. Regardless that the code under is written in Typescript, it might probably simply be adjusted to Javascript so don’t fear if Typescript shouldn’t be your factor. We use async features which is an ES2017 characteristic, so it could be value studying a bit about them.

See also  Pinecone: New vector database architecture a 'breakthrough' to curb AI hallucinations

Full API documentation will be discovered at Fatsecret Platform API docs.

What you want earlier than begin

As talked about earlier than, you’ll need a Fatsecret Developer account. You have to it to get Entry Token often known as REST API Shopper Key and Entry Secret typically known as REST API Shared Secret. From the documentation:

Entry Token: A price which identifies a consumer of your utility (you employ the REST API Profile Administration strategies to generate these).

Entry Secret: A secret we concern with the Entry Token which helps us set up you can carry out a request on behalf of the consumer recognized by the Entry Token (you employ the REST API Profile Administration strategies to generate these and/or retrieve these on your customers).

Each OATH_VERSION and OAUTH_SIGNATURE_METHOD can’t be modified. We may have it hardcoded in our requests, however having it as const on the prime of the file will make the code simpler to grasp and keep.

To correctly signal a request in accordance with FatSecret documentation, we have to add acceptable HTTP question parameters to it. On this tutorial, we are going to cowl solely Signed Requests. So long as you don’t want any information particular to the consumer (like getting consumer’s weight historical past immediately from FatSecret), you’ll not want Delegated Requests. Extra details about these two sorts of request will be discovered within the documentation.

Signature Base String

We have to generate Signature Base String by concatenating the HTTP methodology (GET or POST), the request URL and our question params within the following format:

<HTTP Methodology>&<Request URL>&<Normalized Parameters>

Request URL is solely API_PATH.

See also  Understanding Recent AI Regulations and Guidelines - Healthcare AI

Question Params aka Normalized Parameters

Every methodology (like meals.search or meals.get) in FatSecret REST API has it’s personal set of supported params, however all of them share widespread OAuth parameters. Let’s create a helper perform to get all of them.

We use fixed values outlined earlier than. The one factor that could be unclear right here is oauth_nonce which is a randomly generated string for a request that has been created from the timestamp and a random worth.

We have to convert a plain Javascript object from getOauthParameters to a question string. For that, we are going to use the favored query-string library.

 yarn add query-string 
 yarn add --dev @sorts/query-string

Second-line will add elective Typescript definitions to the library (it isn’t included within the lib).

Now, let’s put together a perform to get the request signature.

We concatenate HTTP methodology, API Path (Request URL), and question params (Normalized Parameters) right into a single string.

encodeURIComponent permits us to encode strings to be correct URIs, with out unsafe characters (like ?=/&). You don’t want it to put in or import it. It’s a part of Javascript normal built-in objects, accessible even in Web Explorer 5.5.

hmcsha1 perform comes from an exterior library, which should be added to bundle.json:

 yarn add hmacsha1

and imported within the supply code:

 import hmacsha1 from 'hmacsha1';

If you happen to don’t need to add exterior requirement to your venture’s bundle.json, you possibly can outline hmacsha1 perform in your supply code as a one-liner.

API Name wrapper

We’re virtually there! All we want now could be to name the FatSecret API.

methodParams is an object of method-specific question parameters. Will probably be a unique set of properties for meals search and totally different for different strategies.

See also  AI and Automation in Healthcare - Healthcare AI

After computing the signature, we add oauth_signature to queryParams .

As you possibly can see, we used the fetch library to work together with the API. You need to use any HTTP shopper you need (axios for instance).

Search methodology

On this tutorial, we are going to cowl just one methodology, meals.search which appears to be entry level for additional growth. Different strategies are very comparable and our code will be reused for them.

question is our search expression. If we need to seek for hamburgers, it is going to be hamburger. This one will most likely come from enter element. maxResults is a quantity worth, which doesn’t want a lot rationalization.

Fetch returns a Promise so we have to await it’s outcomes. On the finish, we return response.json() from our perform, which is Promise, that have to be utilized in our outcome displaying element. As you possibly can see, we outlined FatsecretResponse interface as results of our perform. You can also make it return Response , however you’ll not have kind checks, which Typescript supplies.

 export interface FatsecretFood { 
 food_id: string; 
 food_name: string; 
 food_type: FatsecretFoodType; 
 food_url: string; 
 brand_name?: string; 
 food_description: string; 
 }
 export enum FatsecretFoodType { 
 Model = 'Model', 
 Generic = 'Generic', 
 }
 export interface FatsecretResponse { 
 meals: { 
 meals: FatsecretFood[]; 
 max_results: quantity; 
 total_results: quantity; 
 page_number: quantity; 
 }; 
 }

Full instance

That’s it! You possibly can execute API calls to FatSecret. In case you missed one thing, right here’s a full instance with an additional methodology to get single meals information (by meals ID).


FatSecret Meals Database REST API Shopper with Typescript was initially revealed in DLabs.AI on Medium, the place persons are persevering with the dialog by highlighting and responding to this story.

Source link

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Please enter CoinGecko Free Api Key to get this plugin works.