Make Forward Compatible React API Connectors

React Aptor

react aptor logo

Minimal API Connector for react


آموزش فارسی

Don’t waste your time by finding react version of your favorite javascript package, keep control of your API now.

Documentation: You can find the react-aptor documentation on the website.

Why

Most packages are developed separately in JavaScript for increasing generality being library/framework agnostic.

Connecting vanilla third parties to react is not a routine task especially those that need to change the DOM. On the other hand, these packages might be developed by different teams, hence development progress can be one step behind of the original or even be terminated at any time. Also, wrong abstraction or bad design patterns may interrupt the progress of these react-something packages.

If you are still not convinced you can read this article

Other Concerns:

  • Finding DOM nodes by ReactDOM.findDOMNode
  • Extensively usage of memorization to improve performance or prevent extra re-renders
  • Other duplication layer for all API definition in react that increase the project size
  • Rely on a global scope (e.g. window) for internal settings (making it impossible to have more than one instance)
  • backward compatible updates of the base package need another update for react-* package

react-aptor

We strive to solve all mentioned problems at once and for all.

Features

Small Zero-dependency with less than 1 kilobyte in size (327 B 😱) [react-aptor](https://bundlephobia.com/result?p=react-aptor)
Manageable Your used/defined APIs are entirely under your control. Make it possible to define a slice of APIs which you are surely going to use.
React-ish Developed with lots of care, try to be zero-anti-pattern in react.
Simple It's as simple as that. 💛
Typescript Feel free to contribute or suggest any changes in [issues page](https://github.com/amirHossein-Ebrahimi/react-aptor/issues)

How to use

Connect your react app to any third party in three-step

  1. Define the instantiate function
  2. Define the get API function
  3. Connect API to react by useAptor

  1. Define the instantiate function.
import Something from 'some-third-party';

export default function instantiate(node, params) {
  return new Something(node, params);
}

This function will return an instance of the third-party package. You have access to node (DOM-node*) and params.

The node is passed by react-aptor as a reference to DOM that is occasionally used as a wrapper for embedding UI. The DOM-node* will become more clear in the third step.

The params are optional parameters that are passed by react-aptor and define by you. see the third step. The params will be passed by you and will be more clear in third step.

name this file construct.js as convention ✨.

  1. Define the get API function.
export default function getAPI(instance, params) {
  // return corresponding API Object
  return () => ({
    api_key: () => {
      /* api definition using instance and params */
      console.log(instance);
    },
  });
}

The react-aptor will pass the latest instance of your third-party which has been defined in the first step by instantiate function along with params to getAPI function.

The instance is returned instance of your third-party. Technically it is exactly going to be instantiate(node, params)

The params are optional parameters that are passed by react-aptor and define by you. see the third step. The params will be passed by you and will be more clear in third step.

name this file api.js as convention ✨.

  1. Connect API to react by useAptor
import useAptor from 'react-aptor';
import getAPI from './api';
import instantiate from './construct';

const Connector = (props, ref) => {
  const aptorRef = useAptor(ref, {
    getAPI,
    instantiate,
    /* params: anything */
  });

  return <div ref={aptorRef} />;
};

export default React.forwardRef(Connector);

name this file connector.jsx as convention ✨ If you are using react 17 or newer version, you can also name it connector.js

useAptor in one look

const aptorRef = useAptor(ref, configuration, deps);

ref For the connection phase, you need to define a forwardRef component. The useAptor hook needs forwarded-ref as the first argument, this is necessary to bind all your defined api to this ref.

configuration As the configuration argument you need to pass defined instantiate (defined in the first step ☝️), getAPI (defined in the second step ☝️) and your custom params argument. The useAptor hook will return you a ref (aptorRef) which you can bind to your DOM node.

The params doesn’t have any limitation, it can be any arbitrary type e.g. undefined, number, string or an object containing all of them. The params will be then passed to your instantiate and getAPI function, as you saw in the first and second steps. Params is the best place to connect props to your low-level api it means ”No Need” for extra function generation 🥳

deps Is the same as Dependencies array default value is [] but you can override it as the third and lat argument of useAptor. It maybe needed in situation which you want to force re-instantiate by some prop change. It will use shallow comparison (as react do) for deps array and will call your instantiate & getApI in a row.

API usage

const Main = () => {
  const ref = createRef();

  const apiKeyHandler = () => {
    if (ref.current) {
      ref.current.api_key();
    }
  };

  return (
    <div>
      <Connector ref={ref} />
      <Button onClick={apiKeyHandler}>api call</Button>
    </div>
  );
};

Pass createRef to the Connector component (made in the third step), and then you can access all of the APIs inside ref.current

💡 Using of optional chaining

function call can be much more readable with optional chaining & related babel plugin

const apiKeyHandler = () => ref.current?.api_key();

💡 Better naming

In case you need ref.current more than one time, it is a good idea to rename it at the first place

const apiKeyHandler = () => {
  const { current: api } = ref; // store ref.current in `api`
  if (api) {
    api.api_key();
  }
};

💡 Can I remove if check in handlers

Cause the default value for ref can be undefined (in createRef) and null (in useRef) Typescript will complain about possibility for not-existence of apis. see more. In normal world react will bind your API to given ref after the Connector mount

If you’re using ref in useEffect or somewhere which is guaranteed to have the ref bounded to values, you can return proxy object in your getAPI function to bind all api functions simultaneously.

export default function getAPI(thirdParty, params) {
  if (!thirdParty)
    return () =>
      new Proxy(
        {},
        {
          get: (_, prop) => {
            // Possible to mock differently for different props
            return noop;
          },
        }
      );

  return () => ({
    api_key() {
      // third-party is defined here for sure :)
      console.log(thirdParty);
    },
  });
}

💡 Micro api instructions

You can access all of you apis via this keyword

export default function getAPI(sound, params) {
  return () => ({
    _state() {
      return sound.getState();
    },

    play() {
      if (this._state() === 'LOADED') sound.play();
    },
  });
}

It’s better to start name of this internal functions with _

💡 The this problem in API object

In a case you see this keyword usage in third-party API you must specifying this something other than returned API object. The following examples is for howler integration using react-aptor:

{
  // ❌ It doesn't work
  state: howler.state,

  // 🆗 this is Okay
  state: howler.state.bind(howler),
  // 🆗 this is also Okay
  state: () => howler.state(),
  // 🆗 this is also Okay, too
  state() {
    return howler.state();
  }
}

💡 How to get API-Object type

You can use something like the follwing:

export type APITypes = ReturnType<ReturnType<typeof getAPI>>;

💡 How to make a custom react integeration packge using react-aptor

  1. Name you packge raptor-something :)
  2. Use minimum possible configuration for your api
  3. Interact to props change in your component using useEffect and proper deps array
  4. Bind another ref to you Connector using fork-ref idea, for other possible usage

See all in action in raptor-howler-example

core

ref required

The react useRef or createRef ref instance which has been passed throw react.forwardRef method. your api will be stored in this ref.

configuration required

  • instantiate required

    function(node, params): Instance

    A function that receives probable bounded-node and params. It then returns an instance of your third-party.

  • destroy

    function(previousInstance, params): void

    A function that receives previous created instance and params. It is useful when you want to perform the cleanup before new instance creation. e.g. remove event listeners, free up allocated memories, destroy internally & etc

  • getAPI required

    function(Instance, params): ApiObject

    A function which receives instance of you third-party and params. It then returns a key-value pair object for api handlers.

  • params any

    Params can have any arbitrary type and can be used with props or pre-defined options.

deps []

React dependencies array for re-instantiating your third-party-packages. It will call instantiate with latest node, params when ever shallow comparison for with the previous deps array finds inequality.


Donation

🎨 Designer (BTC): bc1q9fahyct3lrdz47pjf4kfxvsyum2dm74v2hv9xl

💻 Developer/Maintainer (BTC): bc1qq8qq63ex7svkkjdjn5axu8angfxytvs83nlujk

Download Details:

Author: amirHossein-Ebrahimi
Download Link: Download The Source Code
Official Website: https://github.com/amirHossein-Ebrahimi/react-aptor

#react #api #javascript #web-development #webdev

What is GEEK

Buddha Community

Make Forward Compatible React API Connectors
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

Marcelle  Smith

Marcelle Smith

1598083582

What Are Good Traits That Make Great API Product Managers

As more companies realize the benefits of an API-first mindset and treating their APIs as products, there is a growing need for good API product management practices to make a company’s API strategy a reality. However, API product management is a relatively new field with little established knowledge on what is API product management and what a PM should be doing to ensure their API platform is successful.

Many of the current practices of API product management have carried over from other products and platforms like web and mobile, but API products have their own unique set of challenges due to the way they are marketed and used by customers. While it would be rare for a consumer mobile app to have detailed developer docs and a developer relations team, you’ll find these items common among API product-focused companies. A second unique challenge is that APIs are very developer-centric and many times API PMs are engineers themselves. Yet, this can cause an API or developer program to lose empathy for what their customers actually want if good processes are not in place. Just because you’re an engineer, don’t assume your customers will want the same features and use cases that you want.

This guide lays out what is API product management and some of the things you should be doing to be a good product manager.

#api #analytics #apis #product management #api best practices #api platform #api adoption #product managers #api product #api metrics

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api