[ad_1]
Have you ever ever puzzled, how you can present your product a wealthy meals and meals database? After we determined to have meals search performance in considered one 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 go well with our wants finest. We would have liked one thing that’s free for essentially the most fundamental functionalities to validate our product with customers. After some analysis, we realized, that FatSecret is perhaps the only option if we wish to use 100% free service (essentially the most fundamental pricing tier) for now. It may not go well with all of your wants, however we by no means declare that it’s the finest service of all. Some details about FatSecret from their homepage:
The #1 meals and vitamin database on this planet, 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 have 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 appears to be like wealthy, it takes a while to undergo it. Right here’s why this tutorial article comes by. Although the code beneath is written in Typescript, it will possibly simply be adjusted to Javascript so don’t fear if Typescript shouldn’t be your factor. We use async capabilities which is an ES2017 function, so it is perhaps price studying a bit about them.
Full API documentation may be discovered at Fatsecret Platform API docs.
What you want earlier than begin
As talked about earlier than, you will want a Fatsecret Developer account. You have to it to get Entry Token also referred to as REST API Shopper Key and Entry Secret generally known as REST API Shared Secret. From the documentation:
Entry Token: A worth which identifies a person of your utility (you employ the REST API Profile Administration strategies to generate these).
Entry Secret: A secret we situation with the Entry Token which helps us set up which you could carry out a request on behalf of the person recognized by the Entry Token (you employ the REST API Profile Administration strategies to generate these and/or retrieve these to 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 high of the file will make the code simpler to grasp and preserve.
To correctly signal a request in keeping with FatSecret documentation, we have to add applicable HTTP question parameters to it. On this tutorial, we are going to cowl solely Signed Requests. So long as you don’t want any knowledge particular to the person (like getting person’s weight historical past instantly from FatSecret), you’ll not want Delegated Requests. Extra details about these two sorts of request may 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.
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 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 are going to use the favored query-string library.
yarn add query-string yarn add --dev @varieties/query-string
Second-line will add optionally available 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 customary built-in objects, out there even in Web Explorer 5.5.
hmcsha1 perform comes from an exterior library, which have to be added to bundle.json:
yarn add hmacsha1
and imported within the supply code:
import hmacsha1 from 'hmacsha1';
When you don’t wish to add exterior requirement to your venture’s bundle.json, you’ll be able to outline hmacsha1 perform in your supply code as a one-liner.
API Name wrapper
We’re nearly there! All we’d like now could be to name the FatSecret API.
methodParams is an object of method-specific question parameters. It will likely be a special set of properties for meals search and totally different for different strategies.
After computing the signature, we add oauth_signature to queryParams .
As you’ll be able to see, we used the fetch library to work together with the API. You should utilize any HTTP consumer 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 improvement. Different strategies are very related and our code may be reused for them.
question is our search expression. If we wish to seek for hamburgers, it is going to 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 should be utilized in our end result displaying part. As you’ll be able to 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 offers.
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 knowledge (by meals ID).
FatSecret Food Database REST API Client with Typescript was initially printed in DLabs.AI on Medium, the place persons are persevering with the dialog by highlighting and responding to this story.
[ad_2]
Source link