Home Healthcare FatSecret Food Database REST API Client with Typescript

FatSecret Food Database REST API Client with Typescript

by WeeklyAINews
0 comment

Have you ever ever puzzled, the best way to present your product a wealthy meals and meals database? After we determined to have meals search performance in one in every of our merchandise, Suguard (diabetes diary app, underneath improvement in React Native with Firebase and Typescript), we had to do a little analysis on what service would swimsuit our wants finest. We would have liked one thing that’s free for essentially the most primary functionalities to validate our product with customers. After some analysis, we realized, that FatSecret is perhaps the only option if we need to use 100% free service (essentially the most primary pricing tier) for now. It may not 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 nations contributing in extra of 500 million API calls each month.

Authentication

To make use of FatSecret API you’ll want 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. Though the code under is written in Typescript, it will probably simply be adjusted to Javascript so don’t fear if Typescript isn’t your factor. We use async features which is an ES2017 function, so it is perhaps price studying a bit about them.

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 will have 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 worth 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 in your customers).

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

See also  SAS aims to make AI accessible regardless of skill set with packaged AI models

To correctly signal a request in line with FatSecret documentation, we have to add acceptable HTTP question parameters to it. On this tutorial, we’ll 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 just API_PATH.

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 frequent OAuth parameters. Let’s create a helper perform to get all of them.

We use fixed values outlined earlier than. The one factor that is perhaps 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’ll use the favored query-string library.

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

Second-line will add non-compulsory 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.

See also  Bridging Communication Gap with Client Engagement Bot in Home Care

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 package deal.json:

 yarn add hmacsha1

and imported within the supply code:

 import hmacsha1 from 'hmacsha1';

For those who don’t need to add exterior requirement to your challenge’s package deal.json, you possibly can outline hmacsha1 perform in your supply code as a one-liner.

API Name wrapper

We’re nearly 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 distinct set of properties for meals search and totally different for different strategies.

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 should use any HTTP shopper you need (axios for instance).

Search methodology

On this tutorial, we’ll cowl just one methodology, meals.search which appears to be entry level for additional improvement. 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, will probably be hamburger. This one will in all probability come from enter part. 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 part. As you possibly can see, we outlined FatsecretResponse interface as results of our perform. You may make it return Response , however you’ll not have sort 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).

See also  The NHS can now access ‘pioneering’ AI stroke diagnosis software

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

how to implement ai

Source link

You may also like

logo

Welcome to our weekly AI News site, where we bring you the latest updates on artificial intelligence and its never-ending quest to take over the world! Yes, you heard it right – we’re not here to sugarcoat anything. Our tagline says it all: “because robots are taking over the world.”

Subscribe

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

© 2023 – All Right Reserved.