3 Ways To Create Your Own API

3 Ways To Create Your Own API

Originally posted on medium.

Three beginner-friendly methods for creating an API from scratch

APIs are everywhere, and they play a vital role in modern-day technology. From payment platforms to stock market updates, everything is an API nowadays, and learning to create one yourself is a fundamental step in the path to becoming a full-stack developer.

Note: If you aren’t sure what an API is, I have a handy introduction for you.

In this article, I will discuss three beginner-friendly ways you can create an API:

  1. JSON Server
  2. Node.js and Express
  3. Python and Flask RESTful

Each of these methods has different use cases and uses different tech stacks. It is up to you which one you’d like to go with.

JSON Server

Requirements: Node installed

JSON Server is a package available through NPM that allows us to create a REST API with CRUD (Create, Read, Update, Delete) operations out of the box super quickly using only a single JSON file.

First, we need to install the package (globally) by running this in the terminal:

npm install -g json-server

Now we need some data to serve. Create a db.json file with some data (this can be whatever you’d like your API to serve):

{ 
"dogs": [
{ "id": 1,
"breed": "pembroke-welsh-corgi",
"name": "Charles"
},
{ "id": 2,
"breed": "pug",
"name": "cheese"
},
{ "id": 3,
"breed": "dachshund",
"name": "ralph"
}
],
"cats": [
{ "id": 1,
"breed": "ragdoll",
"name": "mimi"
},
{ "id": 2,
"breed": "siamese",
"name": "mocha"
},
{ "id": 3,
"breed": "russian-blue",
"name": "bean"
}
]
}

In order to get our server up and running, run:

json-server --watch db.json --port 8080

If we now make a request to http://localhost:8080/dogs/1, we should get back:

{ "id": 1, "breed": "pembroke-welsh-corgi", "name": "charles" }

The following HTTP endpoints will be created automatically by JSON server too:

GET /dogs 
GET /dogs/{id}
GET /cats
GET /cats/{id} POST /dogs
POST /cats PUT /dogs/{id}
PUT /cats/{id} PATCH /dogs/{id}
PATCH /cats/{id} DELETE /dogs/{id}
DELETE /cats/{id}

With JSON Server, we can filter results by adding query parameters to our requests. If we hit http://localhost:8080/cats?breed=siamese, it should return an array of all the cat objects in the data that match the given criteria.

We can also do a full-text search with the p parameter: http://localhost:8080/cats?q=m.

All of this information and more can be found in much greater detail in the JSON Server GitHub repo.

If you’d like to look into this a little further and find out how to deploy your JSON Server API, I recommend Ania Kubow’s YouTube tutorial on how to create and deploy a mock API.

Node.js and Express.js

Requirements: Node installed

For this method, we will be creating a new Express app. To do this, create a project folder called node-api and a server.js file inside it. After this is done, open a new terminal inside our node-api folder and run:

npm init

This will initialise our project and create a package.json file (for setup questions, it’s OK to just press enter and leave everything blank/default).

Now we need to install Express! We can do this with NPM by running:

npm install express

And in our server.js file, we can now create our server as follows:

var express = require("express");var app = express();app.listen(8080, () => {
console.log("Server running on port 8080!");
});

We have everything we need all set up with Express. Now we are going to create the endpoints for our requests. In this tutorial, we will be creating endpoints for GET requests only.

We can add the data to our file by using two constant variables containing the objects for our data like so:

const dogs = [
  {
    id: 1,
    breed: 'pembroke-welsh-corgi',
    name: 'charles'
  },
  { 
    id: 2,
    breed: 'pug',
    name: 'cheese'
  },
    id: 3,
    breed: 'dachshund',
    name: 'ralph'
  }
];
const cats =
  {
    id: 1,
    breed: 'ragdoll',
    name: 'mimi'
  },
  { 
    id: 2,
    breed: 'siamese',
    name: 'mocha'
  },
    id: 3,
    breed: 'russian-blue',
    name: 'bean'
  }
];

Right after var app = express();, let’s add some functions to handle GET requests to send back all the data on the requested resource with a “200 OK” status code:

app.get("/dogs", (req, res) => {
  res.status(200).json(dogs);
});
app.get("/cats", (req, res) => {
  res.status(200).json(cats);
});

In order to GET specific entries by ID, we have to use the :id URL parameter to search our arrays to find an entry that matches the given ID. Underneath our standard GET requests, add these in:

app.get('/dogs/:id', (req, res) => {
  let id = req.params.id;
  let response = dogs.find((item) => item.id == id);
  
  res.status(200).json(response);
});
app.get('/cats/:id', (req, res) => {
  let id = req.params.id;
  let response = cats.find((item) => item.id == id);
  
  res.status(200).json(response);
});

We can now visit http://localhost:8080/dogs/ and http://localhost:8080/dogs/1 or http://localhost:8080/cats/ (etc.) and see our API working properly. We have created a very simple Node API!

If you want to develop this further and add more endpoints and functionality to your Node API, I recommend Ankit Maheshwari’s CRUD Rest API tutorial from JavaScript In Plain English.

Python and Flask RESTful

Requirements: Python 3 and PIP installed

For starters, we are going to need to install Flask-RESTful by running:

pip install flask-restful

Flask RESTful is a Python module that extends the functionality of the Python Flask module to help us build REST APIs quickly.

To get started, in a new Python project file, create an api.py file and import the following at the top:

from flask import Flask
from flask_restful import Api, Resource

We then have to create an instance of the Flask class and pass that to an instance of a Flask RESTful API:

app = Flask(__name__)
api = Api(app)

Next up, let’s create some lists to store our data:

dogs = [
    {"id": 1, "breed": "pembroke-welsh-corgi", "name": "charles"},
    {"id": 2, "breed": "pug", "name": "cheese"},
    {"id": 3, "breed": "dachshund", "name": "ralph"}
]

cats = [
    {"id": 1, "breed": "ragdoll", "name": "mimi"},
    {"id": 2, "breed": "siamese", "name": "mocha"},
    {"id": 3, "breed": "russian-blue", "name": "bean"}
]

Now on to the more complicated stuff. According to the Flask RESTful documentation, we need to create resource classes to define our HTTP methods. We have to create one resource for the list of cats/dogs and one for the individual ones (by ID):

class DogList(Resource):
  def get(self):
    return dogs, 200


class Dog(Resource):
  def get(self, dog_id):
    return next(item for item in dogs if item["id"] == dog_id), 200


class CatList(Resource):
  def get(self):
        return cats, 200


class Cat(Resource):
  def get(self, cat_id):
    return next(item for item in cats if item["id"] == cat_id), 200

To actually add these resources to be endpoints for our API, we are going to use the add_resource() method and pass in our resources and the respective endpoints we want those resources to be accessed from:

api.add_resource(DogList, '/dogs')
api.add_resource(Dog, '/dogs/<int:dog_id>')

api.add_resource(CatList, '/cats')
api.add_resource(Cat, '/cats/<int:cat_id>')

And finally, we add this line at the end of the file:

if __name__ == '__main__':
app.run(debug=True)

Here, we are enabling Flask debugging mode when we run our code so it reloads when changes are made (like nodemon) and gives us more verbose error messages when things go wrong.

Now, if you try http://localhost:5000/dogshttp://localhost:5000/cats, http://localhost:5000/dogs/1, etc., you will see your API working perfectly!

If you’d like to develop your Python Flask API project further, I recommend RapidAPI’s guide on Python APIs.

Conclusion

And there you have it: REST APIs three different ways! I hope this article helps you get started in developing your own API.

All the example files for these three methods can be found on GitHub.

Source: medium