Building an API With Firebase

In this post, I will build an API with Google’s Firebase. I’ll build the back end with Firebase Cloud Functions and Express.js.

Before I begin, I recommend the following setup:

  1. A terminal set up on either a Windows, Linux, or Mac (OSX) computer
  2. Node 10.10 installed
  3. NVM installed with the instructions here
  4. A Google account
  5. Postman installed
  6. Firebase CLI installed with a run of the terminal command npm install -g firebase-tools

I’ll refer to the code available at this GitHub repo. The GitHub repo also contains a Postman Collection; I recommend importing it and using it to test your project.

Please note that the app id in the URL paths is specific to my deployed project. You’ll need to change the app id to match the project you’re creating in the Firebase Console.

If you don’t understand that yet, it’s okay — I’ll discuss this more after the initial project is set up.

The Basics

To start, I wanted to go over some basic concepts about what APIs are and how the technologies work. This is completely introductory, so feel free to skip this section if you are already familiar.

API stands for Application Programming Interface and refers to the method that computer systems use to communicate with one another.

Google’s dictionary defines APIs as:

“A set of functions and procedures allowing the creation of applications that access the features or data of an operating system, application, or other service.”
You build out an API so your system can communicate with whatever you’re building. APIs can include basic REST endpoints for a website or even the methods that define a software library you’ve built.

Which brings up the next important thing, RESTful services.

RESTful services refer to Representational State Transfer and take advantage of the HTTP protocol to pass data (via an API). The HTTP protocol is what we use every day in websites and internet applications.

RESTful services use different HTTP verbs (or methods) to pass data between different systems.

Typical HTTP verbs include:

  • GET = retrieving data
  • POST = creating or updating data
  • PUT = updating data
  • DELETE = deleting data

I also mentioned endpoints earlier; that’s what I’ll refer to when I mention a website or service I need to hit. An endpoint is just a fancy way to describe an address that my system will hit with an HTTP request.

For more on the ins and outs of HTTP requests, please refer to the wikipedia page.

Firebase

I’m using Google’s Firebase platform for this project. Firebase is a very powerful platform, which developers can use to build applications quickly.

Firebase provides common services that include:

To use Firebase, you simply need a Google account.

In the rest of this post, I’m going to walk through setting up the back end for an API built with Firebase.

Initial Setup

To start, go to the Firebase Console. You should see something like the following:

Click “add project” and give your project a name.

I recommend accepting the analytics, as it helps you and Google. You can refer to the analytics information later on in the console (after your project is created).

Once your project is created, open it in the console and click “database” on the left-hand navigation to see the following:

Click “Create database” under “Cloud Firestore” to create your initial database.

Select “test mode” to enable all reads and writes. You can set rules to specify security on your database to lock it down further later. Please consult the Firebase documentation here for more on locking down your database instances.

You’ll also be asked to set a location; the default should be fine, but you can also try to pick a datacenter closer to you. Check out this page for more on datacenter locations.

With the basic project pieces set up in the console, let’s switch to your computer to set up the code.

Writing Code

In this step, we’ll assume you already have the Firebase CLI on your machine. I recommend following the instructions here to set that up if you haven’t done so already.

Next, go to your terminal and create a folder for your project with mkdir my-project.

Next, cd into that folder and run firebase init; you should see something like the following:

Select “Functions” in the options menu. Then select the Firebase App that you created before in the list shown on the next terminal output.

The next set of options is fairly straightforward.

  • Select JavaScript
  • Select yes for linting
  • Select yes to install dependencies
  • And you’re good to go!

Next, cd into the created functions folder. When you run the init command, it will generate a functions folder for you to work with. The functions folder should have the following files:

  • index.js
  • node_modules folder
  • package-lock.json
  • package.json

Go ahead in your terminal editor of choice (I highly recommend VS Code) and look at index.js first.

Serverless APIs and Your First Endpoint

Firebase Functions enable you to use the Express.js library to host a serverless API. Serverless is a term for a system that runs without physical servers.

This is a bit of a misnomer because it technically does run on a server; however, you’re letting the provider handle the hosting. Traditional APIs would require you to set up a server either in the cloud or on prem that can host your application.

This means that developers would have to be in charge of OS patches and alerts, etc. With serverless, you don’t have to worry about anything but your code. This is one of the coolest parts of Firebase!

So, to use Express.js with your project, erase the index.js file and paste the following lines there:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: true }));

app.get('/hello-world', (req, res) => {
  return res.status(200).send('Hello World!');
});

exports.app = functions.https.onRequest(app);

The first lines that use require pull in the dependencies. We don’t yet have express or cors so let’s install them in the terminal with the following commands:

npm i express
npm i cors

The initial lines with the require value import the libraries we’re going to use.

Here are the libraries in more detail:

  • firebase-functions is an npm module that enables you to create functions.
  • firebase-admin is the Firebase admin SDK that enables your functions to control all of your back-end Firebase services.
  • express is the Express.js library that lets you create a server instance.
  • cors is an npm module that allows your functions to run somewhere separate from your client. The app.use enables CORS for your Express server instance.

The section of the code with app.get creates a “hello world” endpoint. We’re using Express routing here. There are many ways to do this. I’m explicitly defining the routes for the sake of ease.

In an enterprise environment, you would likely use the Express router and the code would probably look a little less verbose. For a more detailed dive into Express routing

For our purposes, the app.get is makes an HTTP GET** **request and captures the request in req and response in res.

When the endpoint is called, it will return a “Hello World!” string with an HTTP status code of 200. Status codes in HTTP are used to determine responses. There are many, but for this tutorial, 200 is success and 500 will return error.

The section with exports.app = functions.https.onRequest(app); exposes your Express application so it can be accessed. If you don’t have the exports section, your application won’t start correctly.

With packages installed and initial code set up, we can run our project with npm run serve. This will serve your functions locally and should result in the output as follows:

Now if you notice, I did get a warning about my Node version. Ignore that for now; I’ll come back to that when we start accessing the database.

Also, notice that the terminal outputs the localhost address of your API that is running locally. You’re going to call that directly from Postman as this is the “address” of your API.

When running on localhost, the URLs for your app will look like the following:

[<------domain---->]/[<-app id--->]/[<-zone-->]/app/[<-endpoint->]
http://localhost:5000/fir-api-9a206/us-central1/app/create

When we go to deploy, the only difference in the URL will be that <a href="http://localhost:500" target="_blank">http://localhost:500</a> will be replaced with zone + app id + cloudfunctions.net, similar to the following:

[<---zone + app id + cloudfunctions.net----->]/app/[<--endpoint-->]
https://us-central1-fir-api-9a206.cloudfunctions.net/app/hello-world

You’ll need to update the Postman collection with your app ID values. To see your app ID, go to the Firebase Console and click “project settings,” as in the following screenshot:

Once there, the project ID (and some other settings) will be listed. I’ve circled it in this screenshot:

Open up the Postman collection and edit the hello-world localhost request under the localhost folder.

As I mentioned, change the ID value to match your project. The address that was listed in the terminal when you ran npm run serve should have this information as well.

When you’re done, run the request from Postman and you should see the following:

Now that we have our initial endpoint set up, let’s go ahead and add database calls.

Database Calls

For the API we’re building, it’s just operations for a list of items. We’re going to set up Create, Read, Update, and Delete (or CRUD) functions for this list of items.

In Firebase, you have two options for database use. You can use a traditional database, or you can use Cloud Firestore.

For this tutorial, we’re going to use Cloud Firestore because it’s easier to work with and more versatile. Cloud Firestore is a NoSQL database, which means that your data is stored as documents within collections.

This is similar to how data is stored in rows in tables in an SQL database. NoSQL databases typically perform better and are easier to scale due to the nature of their data access and storage.

In the setup section, we added a Cloud Firestore instance to our project. To interact with the Cloud Firestore using the admin SDK locally, you’ll need to access it via a service account.

Service accounts have keys that they use; you run these permissions by downloading a key file.

To do this, go to the Firebase Console and open your application. Then click the little gearbox and “users and permissions” as you see here:

Then click the “service accounts” tab, and you should see something like the following:

If you notice, at the bottom of the screen they provide you with some code to run in your project. The only thing you’ll need is the permissions file to reference.

Go ahead and click “Generate new private key” to be able to install that in your project. Then, store that next to the index.js file in your functions folder we were just working with.

You can name it whatever you want; I named mine permissions.json.

Then, add the following to the top of your index.js file:

var serviceAccount = require("./permissions.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://fir-api-9a206..firebaseio.com"
});
const db = admin.firestore();

These lines (1) load in your permissions file and then (2) use it to initialize your application. I also created a variable db to represent our Firestore instance. This isn’t necessary but makes the code cleaner later on.

With those values loaded up, let’s add a create endpoint to our application. Below the hello-world endpoint, add the following:

// create
app.post('/api/create', (req, res) => {
    (async () => {
        try {
          await db.collection('items').doc('/' + req.body.id + '/')
              .create({item: req.body.item});
          return res.status(200).send();
        } catch (error) {
          console.log(error);
          return res.status(500).send(error);
        }
      })();
  });

This code creates an endpoint /api/create-item that you make a POST call to. When the POST call is made, it adds the item from the body to a collection in the database called “items” with an ID of the value you passed in, called id here.

Collections in a NoSQL database are just collectors of documents. You could just as easily do this with a specific document. I tend to like collections when using Firestore because they’re easy to understand. You can also think of collections similarly to tables in an SQL Database.

If you also notice, I’ve prefixed the endpoint with /api. This is not required but is typically convenient with any API you create.* *I’m also specifying the ID value with my requests. Firebase will do this for you, but I thought it was easier to understand if we explicitly define this in the requests.

So with this code added, let’s stop the server in the terminal (if you haven’t already) and restart it with a new npm run serve.

In the Postman collection, pull up the “create localhost” POST request. Modify the app id value as you did before, and attempt the request.

When you run it, you should see the following error:

The Firebase admin SDK requires Node version 8.13.0 or 10.10. This is why I asked to install nvm in the first section. This is very easy to fix. nvm enables you to quickly switch Node versions in your local terminal.

In your terminal, run nvm use 10.10, and you should see the following:

Now start your server again with npm run serve and hit the endpoint on Postman. You should see a 200 success. In the terminal, you can also see that the API was hit locally.

If you run into an error about onRequestWithOpts or something similar, do an npm i firebase-tools.

An error recently came up with the CLI: version 7.1.0 fixed this. When writing this post, I found I needed to update my Firebase CLI version to fix this. Check out this issue for more.

One additional cool feature is that you can directly see your data in Cloud Firestore. If you hop over to the Firebase console, click the “database” link on the left-hand navigation and you should see something like the following:

Building the DB Endpoints

So now that we have the create endpoint set up, let’s add the rest of the operations:

  • /read-item/:item_id = read a specific item (by ID)
  • /read-items = read all items (total collection)
  • /update-item/:item_id = update an item
  • delete-item/:item_id = delete an item

For the most part, all of the endpoints will be similar. The exception is when I pass query params with the item_id value. This all follows basic routing, which you can see in the Express.js documentation.

Additionally, for actually interacting with the Firebase Admin SDK, I recommend the Firestore API reference here.

For a look at what these endpoints should look like (when finished) check out the <a href="https://github.com/andrewevans0102/how-to-build-a-firebase-api/blob/master/functions/index.js?source=post_page---------------------------" target="_blank">index.js</a> file on the GitHub repo here.

Here’s the code for the rest of the endpoints:

---

// read item
app.get('/api/read/:item_id', (req, res) => {
    (async () => {
        try {
            const document = db.collection('items').doc(req.params.item_id);
            let item = await document.get();
            let response = item.data();
            return res.status(200).send(response);
        } catch (error) {
            console.log(error);
            return res.status(500).send(error);
        }
        })();
    });

// read all
app.get('/api/read', (req, res) => {
    (async () => {
        try {
            let query = db.collection('items');
            let response = [];
            await query.get().then(querySnapshot => {
            let docs = querySnapshot.docs;
            for (let doc of docs) {
                const selectedItem = {
                    id: doc.id,
                    item: doc.data().item
                };
                response.push(selectedItem);
            }
            });
            return res.status(200).send(response);
        } catch (error) {
            console.log(error);
            return res.status(500).send(error);
        }
        })();
    });

// update
app.put('/api/update/:item_id', (req, res) => {
(async () => {
    try {
        const document = db.collection('items').doc(req.params.item_id);
        await document.update({
            item: req.body.item
        });
        return res.status(200).send();
    } catch (error) {
        console.log(error);
        return res.status(500).send(error);
    }
    })();
});

// delete
app.delete('/api/delete/:item_id', (req, res) => {
(async () => {
    try {
        const document = db.collection('items').doc(req.params.item_id);
        await document.delete();
        return res.status(200).send();
    } catch (error) {
        console.log(error);
        return res.status(500).send(error);
    }
    })();
});


---

Deploying

So now we have a fully functional CRUD API. We’re ready to deploy!

If you’re developing an enterprise application (or one that you’ll be maintaining), it is typical to build a Continuous Integration Continuous Deployment (CICD) pipeline. This is a set of steps that are automated for delivering your application into production.

With our API, we’re interested in the actual deployment step. The Firebase CLI takes care of this for you with a firebase deploy.

When you ran the firebase init command to initially build your project, the Firebase CLI already set up the deploy step as an npm script. We can now deploy that created project with npm run deploy from the functions folder.

npm scripts are very powerful. Most modern JavaScript applications use them in one way or another. I recommend checking out the npm documentation for more.

When you run npm run deploy from the functions folder, you should see something like the following output:

The line of the terminal output Function URL provides the endpoint of your deployed functions. Go back to the Postman collection and check out the deployed folder for a set of requests to hit your deployed API.

Connecting a Front End

Now that we’ve built out the API, I wanted to showcase what it would look like if you were to use it in a client application.

When discussing APIs, typically you will have a producer and a consumer. The producer is the API itself (or at least what provides the endpoints). The consumer is anything that uses those endpoints. Typically application developers will build a client application using JavaScript frameworks such as Angular, React, Ember.js, Vue.js, and others.

Client applications are run in the browser and enable JavaScript code to be interpreted on the fly. This is particularly useful because many times developers need somewhere to statically host their JavaScript bundle.

This takes advantage of the JavaScript language as well as many advances that have happened with browsers today.

If you remember from the first sections, we’re using the code I put on this GitHub repo. This GitHub project has both our back-end API code and a front-end Angular application that I built to interact with the API.

The basic application consists of one main page and is considered a Single Page Application (SPA). The application does basic CRUD operations on list items.

While running the application, you can also see it in action in the browser’s console. If you open the console (right-click “inspect” if you’re using Chrome), you should see the following:

To use the client I built, first cd into the frontend folder of my GitHub project.

To make the application run against the endpoints of the API you deployed, you just need to open the /frontend/src/environments/environment.ts file.

In this file, you’ll see a set of endpoints. To use the client I built, first cd into the frontend folder of my GitHub project.

To make the application run against the endpoints of the API you deployed, you just need to change these values to match the URLs from your project.

If you remember, once you deployed your API, the Firebase CLI output a domain to the terminal. The hosted endpoint nomenclature is super intuitive and is as follows:

[<----zone + app id + cloudfunctions.net----->]/app/[<--endpoint-->]
https://us-central1-fir-api-9a206.cloudfunctions.net/app/hello-world

Go ahead and replace the endpoint values in this environments file with the ones from your project. Remember to always end each endpoint with the associated path like /api/create or /api/read, respectively.

Once you’ve replaced the values, cd into the frontend directory and run a standard npm install to install the dependencies. Once the dependencies finish installing, use the Angular CLI command to start the app with ng serve.

If you encounter errors with the CLI, check out the Angular CLI documentation.

After running ng serve, you should see something like the following in the terminal:

This message means the CLI has built the application (with webpack) and it is currently running on port 4200. If you open your browser and go to localhost:4200, you should see the app running.

If you look at the project’s app component, you’ll see that the actions are just doing JavaScript fetch calls to the endpoints from the API we created:

async selectAll() {
    try {
      console.log(environment.readAll);
      console.log('calling read all endpoint');

      this.exampleItems = [];
      const output = await fetch(environment.readAll);
      const outputJSON = await output.json();
      this.exampleItems = outputJSON;
      console.log('Success');
      console.log(outputJSON);
    } catch (error) {
      console.log(error);
    }
  }

  // really this is create but the flow is that
  // click the "create item" button which appends a blank value to the array, then click save to actually create it permanently
  async saveItem(item: any) {
    try {
      console.log(environment.create);
      console.log('calling create item endpoint with: ' + item.item);

      const requestBody = {
        id: item.id,
        item: item.item
      };

      const createResponse =
        await fetch(environment.create, {
          method: 'POST',
          body: JSON.stringify(requestBody),
          headers:{
            'Content-Type': 'application/json'
          }
        });
      console.log('Success');
      console.log(createResponse.status);

      // call select all to update the table
      this.selectAll();
    } catch (error) {
      console.log(error);
    }
  }

  async updateItem(item: any) {
    try {
      console.log(environment.update);
      console.log('calling update endpoint with id ' + item.id + ' and value "' + item.item);

      const requestBody = {
        item: item.item
      };

      const updateResponse =
        await fetch(environment.update + item.id, {
          method: 'PUT',
          body: JSON.stringify(requestBody),
          headers:{
            'Content-Type': 'application/json'
          }
        });
      console.log('Success');
      console.log(updateResponse.status);

      // call select all to update the table
      this.selectAll();
    } catch (error) {
      console.log(error);
    }
  }

  async deleteItem(item: any) {
    try {
      console.log(environment.delete);
      console.log('calling delete endpoint with id ' + item.id);

      const deleteResponse =
        await fetch(environment.delete + item.id, {
          method: 'DELETE',
          headers:{
            'Content-Type': 'application/json'
          }
        });

      console.log('Success');
      console.log(deleteResponse.status);

      // call select all to update the table
      this.selectAll();
    } catch (error) {
      console.log(error);
    }
  }

Since the main point of this post was creating the API, I won’t go into the details of how this Angular application works. I highly recommend you check out the Angular Documentation and the available tutorials.

Closing Thoughts

Photo by Markus Spiske on Unsplash

Congratulations! You’ve just deployed an API with Firebase. There are a lot of additional things you can do with this API, but this shows you the basics.

I hope my post here has helped you get started with building APIs with Firebase.

#node-js #api #javascript #firebase #express

What is GEEK

Buddha Community

Building an API With Firebase

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

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

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

Autumn  Blick

Autumn Blick

1602851580

54% of Developers Cite Lack of Documentation as the Top Obstacle to Consuming APIs

Recently, I worked with my team at Postman to field the 2020 State of the API survey and report. We’re insanely grateful to the folks who participated—more than 13,500 developers and other professionals took the survey, helping make this the largest and most comprehensive survey in the industry. (Seriously folks, thank you!) Curious what we learned? Here are a few insights in areas that you might find interesting:

API Reliability

Whether internal, external, or partner, APIs are perceived as reliable—more than half of respondents stated that APIs do not break, stop working, or materially change specification often enough to matter. Respondents choosing the “not often enough to matter” option here came in at 55.8% for internal APIs, 60.4% for external APIs, and 61.2% for partner APIs.

Obstacles to Producing APIs

When asked about the biggest obstacles to producing APIs, lack of time is by far the leading obstacle, with 52.3% of respondents listing it. Lack of knowledge (36.4%) and people (35.1%) were the next highest.

#api #rest-api #apis #api-first-development #api-report #api-documentation #api-reliability #hackernoon-top-story