python

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
venv\Scripts\activate

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 settings.py, 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.

'rest_framework',
 'myapi',

Next step, open views.py 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.
@api_view(["GET"])
def userData(userdata):
    try:
        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 urls.py 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 = [
    url(r'^admin/', admin.site.urls),
    url(r'^userdata/',views.userData)
]

Now, run the server with python manage.py 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 app.py. Open the file and paste the followings.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, World!"

@app.route("/userdata")
def userData():
  return "username : rasyue"

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

Now, from you command line, run python app.py

flask-server
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 app.py, 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('0.0.0.0', 6543, app)
    server.serve_forever()

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 tornado_test.py. 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):
        print(self)
        response = {'id': '1', 'name': 'Rasyue'}
        self.write(response)

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



    

if __name__ == "__main__":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Start the script above and go to 127.0.0.1:8888/rasyue.
You can use POSTMAN to send a POST request to 127.0.0.1:8888/add-user 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 bottle_test.py 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

@app.route('/')
@allow_cors
def rasyue():
    return "Hello Rasyue!"

@app.get('/hello') # or @route('/login')
@allow_cors
def hello():
    return "Hello World!"

@app.post('/add-user') # or @route('/login', method='POST')
@allow_cors
def add_user():
    print(request)
    return "User Added"

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

Now, run the script with python bottle_test.py 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 *

*

*
*