How to Create API Service in 5 Different Python Frameworks

By Rasyue | On July 5, 2020

Python is one of the most used language and has a lot of web frameworks that can be used to help us in web development. In this post, we are going to go through on how to create an API service using 5 different Python frameworks. You can then consume your API service using your front-end frameworks like React or Angular. Let’s get started!

Before you install any of this frameworks, it’s a common thing to use virtual env when working with Python. There are a lot of virtual env that you can use in Python so you might not want to use the one that I used in this tutorial but for those who are still new to Python, I recommend that you follow this.

mkdir pythonapi
cd pythonapi
python -m venv venv

Please note, throughout this tutorial, I am going to be using the same virtual env so make sure you have the virtual env up and running. With that, we are ready to create our API service.

1. Django

To create an API service with Django, run the following commands.

pip install django
pip install djangorestframework
django-admin startproject djangoapi
cd djangoapi
django-admin startapp myapi

You should be having something like this.

After that, open your, find the INSTALLED_APPS array and add the followings, this is to tell that we are going to be using restframework in the project and also to add the app you created earlier.


Next step, open in myapi folder or if you are using different name for your app.

from django.shortcuts import render
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.http import JsonResponse
from django.core import serializers
from django.conf import settings
import json
# Create your views here.
def userData(userdata):
        username = 'rasyue';
        return JsonResponse("username :"+username,safe=False)
    except ValueError as e:
        return Response(e.args[0],status.HTTP_400_BAD_REQUEST)

Next step, open the in the project folder or the djangoapi folder and add the followings.

from django.conf.urls import url
from django.contrib import admin
from MyApp import views
urlpatterns = [

Now, run the server with python runserver and go to localhost:8000/userdata

2. Flask

To create an API endpoint using Flask, first run the following command

pip install flask
pip install flask-cors

Create a new python file and name it however you like, I am going to name it Open the file and paste the followings.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

def helloWorld():
  return "Hello, World!"

def userData():
  return "username : rasyue"

if __name__ == '__main__':

Now, from you command line, run python

flask server

You can check out my other post here which explains on the full stack of React and Python Flask (How to Build a Full-Stack React With Python Flask App – Series)

3. Pyramid

To create your API service with Pyramid, first run the following commands.

pip install pyramid
pip install waitress

Open your, create it if you have not done so. Copy and paste the followings.

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
    return Response('Hello World!')

if __name__ == '__main__':
    with Configurator() as config:
        config.add_route('hello', '/')
        config.add_view(hello_world, route_name='hello')
        app = config.make_wsgi_app()
    server = make_server('', 6543, app)

Start the script and you test out the server at port 6543.

4. Tornado

Tornado is a Python web framework and asynchronous networking library. By using non-blocking network I/O, Tornado can scale to tens of thousands of open connections, making it ideal for long pollingWebSockets, and other applications that require a long-lived connection to each user.

Run the command below to install tornado

pip install tornado

Create a new file and name it Copy below code.

import tornado.ioloop
import tornado.web
import asyncio

class HelloRasyue(tornado.web.RequestHandler):
    def set_default_headers(self):     
        self.set_header("Access-Control-Allow-Origin", "*")     
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
    def get(self):      
        self.write("Hello, Rasyue")

class AddUser(tornado.web.RequestHandler):
    def set_default_headers(self):     
        self.set_header("Access-Control-Allow-Origin", "*")     
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
    def post(self):
        response = {'id': '1', 'name': 'Rasyue'}

def make_app():
    return tornado.web.Application([
        (r"/rasyue", HelloRasyue),
        (r"/add-user", AddUser),


if __name__ == "__main__":
    app = make_app()

Start the script above and go to
You can use POSTMAN to send a POST request to and it will return back the response. Note the headers to prevent CORS issue.

5. Bottle

Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Python Standard Library.

To create an API service with Bottle, first run the command below.

pip install bottle

Create a new file and copy the code below to start a simple server with GET and POST endpoints.

from bottle import Bottle, run, get, post, request, response

app = Bottle()

def allow_cors(func):
    def wrapper(*args, **kwargs):
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
        return func(*args, **kwargs)
    return wrapper

def rasyue():
    return "Hello Rasyue!"

@app.get('/hello') # or @route('/login')
def hello():
    return "Hello World!"'/add-user') # or @route('/login', method='POST')
def add_user():
    return "User Added"

run(app, host='localhost', port=7060)

Now, run the script with python and you can test it out. Test out the POST endpoint with POSTMAN.

Obviously, in real project, the API service that you need to build will not be as simple as the above but this serves as a starting point for you and the rest is up to you to extend and improve to be able to accomodate your application needs.

See you guys in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *