How to Create an API From Scratch Using Python and Flask

How to Create an API From Scratch Using Python and Flask

Posted in

It’s never been easier to create your own APIs. It’s also never been cheaper, thanks to numerous powerful frameworks, libraries, and packages that have popped up in the wake of the mass adoption and popularity of APIs.

Knowing how to create your own APIs confers all manner of benefits. Understanding what’s happening behind the scenes liberates you from proprietary tools and solutions. It also helps you think like an API designer, as it facilitates visualizing API architecture, endpoints, availability and access to resources, and so on.

In this tutorial, we’re going to show you how to create your own API from scratch using Python and Flask. Python is the third most popular programming in the world, according to Statista, closely ranking behind JavaScript and HTML.

Statista research popular programming languages

Source: Statista

Flask is one of the most popular Python libraries for web development, with almost 66,000 stars on GitHub and 16,200 forks, making it an easy pick for our API tutorial. Even better still, there’s a dedicated library for creating and hosting APIs in Flask, Flask_restful, making it especially convenient to get up and running.

1. Getting Started

Creating your own API from scratch couldn’t be easier. Numerous packages and libraries let you create an API from the command line and a simple text editor. Setup is simple — it’s what you do with the API once it’s deployed where things can get complex.

For this tutorial, we’re going to create an API for creating your own ToDo list using Python, Flask, and Flask-restful. When you’re done, you’ll have a fully functional API, with every time getting its own endpoint.

To start, create a folder for your project in your programming directory. We’ve called ours FlaskApp. Navigate to your new folder. For this exercise, we’re going to create a virtual environment. Inside of your development folder, run the following script:

python -m venv env

To activate, find the Activate.exe file and run it. If you’re on Windows, it’ll be inside .\env\Scripts.

Next, you’re going to install the Flask library. Input the following command into your command prompt.

pip install Flask

Now, we’re going to do the same with Flask-restful, a library meant specifically for creating APIs in Python. Run the following code:

pip install Flask-restful

2. Create a Minimal API in Python

Now, we’re going to create a barebones API in Python using Flask and Flask-restful. Start by creating a new file using your text editor of choice. We’re using Notepad++ as it lets you save files in whatever format you want. Save this file as API.py.

Inside of API.py, insert the following code:

from flask import Flask
from flask_restful import Resource, Api

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

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

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

Save this file. Next, we’re going to run the file using:

python api.py

You should get the following result:

* Running on http://127.0.0.1:5000

Next, open another instance of Command Prompt. Navigate to your programming folder again and run the following code to test the code.

curl http://127.0.0.1:5000/

You should get the following result.

{
    "hello": "world"
}

3. Create Resourceful Routing

Resources are the primary building blocks in Flask-restful. They’re built using Flask’s pluggable views, which lets you use multiple HTTP methods for each resource. Here’s an example of what Resourceful Routing might look like:

from flask import Flask, request
from flask_restful import Resource, Api

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

todos = {}

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

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

This code specifies protocols for both get and push for the ToDo function. Every time a new item is shared to the server, a new ToDo endpoint is created. To test this out, use the following command:

curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT

This should return the following result to the ToDo1 endpoint.

{
    "todo1": "Remember the milk"
}

Although it’s simplistic, this example shows you how you can create a completely workable API, complete with custom endpoints, two libraries, a text editor, and 20 lines of code.

4. Customize Endpoints

Most APIs will feature more than one endpoint. Fortunately, you can create as many custom endpoints as you like in Flask-restful using the api.add_resource method. You can also use individual components of a path to create endpoints, such as the following:

api.add_resource(Todo,
    '/todo/<int:todo_id>', endpoint='todo_ep')

5. Parse Arguments

Flask-restful features native argument parsing using the reqparse method, similar to the argparse method. This ensures your data is appropriately formatted. An example of reqparse in action:

from flask_restful import reqparse

parser = reqparse.RequestParser()
parser.add_argument('rate', type=int, help='Rate to charge for this resource')
args = parser.parse_args()

Reqparse also includes built-in errors if the formatting’s not correct. For example, if you were to send:

curl -d 'rate=foo' http://127.0.0.1:5000/todos

You might get the following result:

{
    "message": "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."
}

6. Example Flask API Using Flask-Restful and Python

Let’s finish up with a slightly more advanced API to help give you some idea of how easy it is to create an API that’s actually useful using Python, Flask, and Flask-Restful.

You might create a secondary file for this example so as not to disturb your first working demo. We called ours API2.py. Create a new file and insert the following:

from flask import Flask
from flask_restful import reqparse, abort, Api, Resource

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

TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}


def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

parser = reqparse.RequestParser()
parser.add_argument('task')


# Todo
# shows a single todo item and lets you delete a todo item
class Todo(Resource):
    def get(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        return TODOS[todo_id]

    def delete(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        del TODOS[todo_id]
        return '', 204

    def put(self, todo_id):
        args = parser.parse_args()
        task = {'task': args['task']}
        TODOS[todo_id] = task
        return task, 201


# TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
    def get(self):
        return TODOS

    def post(self):
        args = parser.parse_args()
        todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
        todo_id = 'todo%i' % todo_id
        TODOS[todo_id] = {'task': args['task']}
        return TODOS[todo_id], 201

##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')


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

Now, run your new file.

Python API2.py

Finally, you can try out your new API. Use this command to get a list of all of the items on your new ToDo list.

curl http://localhost:5000/todos

You should get a response like this:

{
    "todo1": {
        "task": "build an API"
    },
    "todo2": {
        "task": "?????"
    },
    "todo3": {
        "task": "profit!"
    }
}

Final Thoughts On Creating Your Own API From Scratch

As we have seen, you don’t need to spend much time, money, energy, or resources to design and build your own API. You don’t need fancy and expensive proprietary software to create an API that’s actually useful for you and your organization, either. Designing your own API gives you a deep, masterful knowledge of every single aspect of your API, as well.

With powerful tools like Flask and Flask-restful, you don’t even need extensive programming experience to create useful, practical APIs. Most importantly, developing your own API gives you a chance to use your API. All the theory in the world doesn’t compare to even simple, practical, real-world applications. Seeing your API in action helps you understand its strengths and shortcomings in ways that are difficult to anticipate.

Knowing how to create your own API from scratch lets you design and implement your API however you want. This can improve your API’s security and discoverability, in addition to its many other benefits, as you can create your API following popular API standards like OpenAPI. Specifications also act as a template to pattern your API after, offering the best of all worlds. Custom APIs can be powerful, versatile, customizable, secure, and easy to create. There’s every incentive to experiment with creating an API from scratch for yourself!