Skip to content
  • About Us
  • Contact Us
  • Privacy Policy
  • Disclaimer
  • Corona Virus Stats (Covid-19)
  • Work with us
  • FB
  • LinkedIn
  • Twitter
  • Instagram.com
Tekraze

Tekraze

Dive Into Technology

  • Guides
    • Developer Guide
    • PC Guide
    • Web Guide
    • Android Guide
    • Music
    • Tutorials
  • Feed
    • Tech News
    • Shared Tech
    • Gaming Videos
    • Unboxing videos
  • Forums
    • Android Apps
    • Angular Npm Packages
    • Useful Site Links
    • Tech Queries
    • Windows OS Help
    • Web Guide and Help
    • Android Os And Rooting
    • Jhipster Discussion
    • Git & GitHub forum
    • Open Source Forum
  • Tools
    • Apk Downloader
    • Speed Test
  • Games
    • Quiz Games
    • Browser Games
  • Short Videos
  • Work with us
  • Toggle search form
  • Facebook challenges YouTube with Licensed Music
    Facebook challenges YouTube with licensed music videos Tech News
  • Put your Imagination to work & win a chance to visit Google India 1
    Put your Imagination to work & win a chance to visit Google India Tech News
  • 10 Tips on How to Extend the Life of Your Laptop
    10 Tips on How to Extend the Life of Your Laptop Tech News
  • How to Find the Right Talent for the Job
    How to Find the Right Talent for the Job with Ease Tech News
  • Top 3 Signs That Your Beloved Macbook Needs Tuning
    Top 3 Signs That Your Beloved Macbook Needs Tuning Latest tech
  • The Latest Android Update Is Focused on Security
    The Latest Android Update Is Focused on Security Android Guide
  • Hacking of high-profile Twitter users prompts FBI investigation 2
    Hacking of high-profile Twitter users prompts FBI investigation Tech News
  • Top 10 Websites to pay electricity bill online 3
    Top 10 Websites to pay electricity bill online Guest posts
A simple script to create Rest API in Python with Dockerization as Bonus

A simple script to create Rest API in Python with Dockerization as Bonus

Posted on January 21, 2022January 21, 2022 By Balvinder Singh No Comments on A simple script to create Rest API in Python with Dockerization as Bonus

One day, I was working with a code where I had to pull JSON data from Github and make use of it in a react app. But the data also contained different keys so, it was like name, then child data but I wanted some different format. I wanted to have an array of these records together. So, I decided to write API in python. I do not know python much, but remembered one of my friends, all these questions our answer is quickly creating up APIs in python with a few lines, so I gave it a try.

So, what I used to create Rest API in python

  1. Falcon PyPI package
  2. requests Pypi package
  3. Docker
  4. Gunicorn

Here is the code with different methods which I will explain ahead

#author @tekraze

import falcon
import requests

class Hello:
    def on_get(self, req, resp):
        # we just send back a string here
        resp.media = 'hello'

class HelloJSON:
    def on_get(self, req, resp):
        # we just send back a string here
        resp.media = {'greet': 'hello'}
        
class JSONfromURL:
    def on_get(self, req, resp):
      
        # here we get data from url and then send it back as a response
      
        fakeUsersAPIUrl = 'https://jsonplaceholder.typicode.com/users'
        
        usersRequest = requests.get(fakeUsersAPIUrl)
        
        usersResponse = usersRequest.json()
        
        usersRequest.close()

        resp.media = usersResponse
        
class JSONfromURLChange:
    def on_get(self, req, resp):
      
        # here we get data from url and then send it back as a response
      
        fakeUsersAPIUrl = 'https://jsonplaceholder.typicode.com/users'
        
        usersRequest = requests.get(fakeUsersAPIUrl)
        
        usersResponse = usersRequest.json()
        
        usersRequest.close()
        
        # here we additionally create new data and send back to show how manipulation works
        
        # to hold new data
        newDataArray = []

        print(type(usersResponse))
  
        for key in usersResponse[:10]: ## to just get n items instead of whole list
            newData = {}
            newData['serial'] = key['id']
            newData['name'] = key['name']
            newDataArray.append(newData)

        resp.media = newDataArray

middle = falcon.CORSMiddleware(
    allow_origins="*"
)

api = falcon.App(middleware=middle)

api.add_route('/greet', Hello())
api.add_route('/greet-json', HelloJSON())
api.add_route('/json-from-url', JSONfromURL())
api.add_route('/json-from-url-change', JSONfromURLChange())

So, what is happening here

falcon we have imported to run an API server, and request will help us fetch data from the URL in json format

The below code will create an API server

api = falcon.App()

and these lines will map the API endpoints to specific methods

api.add_route('/greet', Hello())
api.add_route('/greet-json', HelloJSON())
api.add_route('/json-from-url', JSONfromURL())
api.add_route('/json-from-url-change', JSONfromURLChange())

So, Falcon is a lightweight package allowing one to create APIs lightweight but powerful when you need to quickly access data without a full app.

Testing in local

To run API we need to host the python script, which we can do using gunicorn.

Install gunicorn

apt install gunicorn
or
pip install gunicorn

Run script

gunicorn main:api

here main is name as main.py file and api is our api server variable we defined.

You can see below output for the same

You can open the URL on port 8000 by default

Output for running API with gunicorn
Output for running API with gunicorn

Table of Contents

  • Methods Explained
    • 1. Hello and HelloJson
    • 2. JsonFromUrl
    • 3. JsonFromUrlChange
  • Bonus
    • Building the image
    • Running the app in docker

Methods Explained

1. Hello and HelloJson

Both methods basically give data in form of string and json. This can be used if we need to pass some data normally or read from a local file and send it.

I have not added the code to read a file but below you can see how to add

with open("test.txt", encoding = 'utf-8') as f:
     
resp.media = f;

2. JsonFromUrl

So, in this method, we are using one fake rest API which provides us with a users list. So we use request to fetch the URL and send the json back as a response from the API.

You can see in the screenshot

Output of JSONfromUrl method
The output of JSONfromUrl method

3. JsonFromUrlChange

In this method, we just add up to the previous method and create a new record from the fake API json. Sometimes we need to get only some data or to process new data from different key-value pairs, then we can use this way.

You can see how the output changed now

A simple script to create Rest API in Python with Dockerization as Bonus 4
The output of JSONfromUrl change method

So, this is how we can create simple rest APIs and tag different methods with Falcon and python


Bonus

So, yes the bonus part on how to dockerize you can check below

FROM python:3.11.0a3-alpine3.15

EXPOSE 8000

# Install gunicorn & falcon
RUN pip install gunicorn requests falcon --trusted-host=pypi.python.org --trusted-host=pypi.org --trusted-host=files.pythonhosted.org

# Add demo app
COPY ./app /app
WORKDIR /app

CMD ["gunicorn", "-b", "0.0.0.0:8000", "main:api"]

We just created a folder with a structure like

- app
  - main.py
- Dockerfile

so, we put our main.py file in the app folder that will be copied to docker.

then we install packages required and execute gunicorn with CMD.

Note: you can also use requirements.txt in place

Building the image

sudo docker build . -t myfalconapi:latest

Running the app in docker

sudo docker run --name falconapi --port 8000:8000 myfalconapi -d

Access the same way on localhost:8000 or via domain if you running a caddy or Nginx

So, this was for now. Thanks for reading.

We are currently running a survey on a tool, feel free to answer

https://yubpg57axrr.typeform.com/to/MNeVchim

Also feel free to visit our company site to know more on services available

https://dehazelabs.com


So, we showed how to create a simple rest API in python using falcon and gunicorn along with docker. We hope it will help you. To read more articles like this stay connected. Have a happy reading. Feel free to share and comment below for your views on this.

Content Protection by DMCA.com
Developer Guide Tags:docker, linux, python, rest api

Post navigation

Previous Post: 3 WAYS HOW TO IMPROVE YOUR ATTENTION
Next Post: Maximize Your Daily Productivity With These Mobile Apps

Related Posts

  • Install Ubuntu in Windows 10
    How to Install Ubuntu in Windows 10 Tutorials
  • Google Map JSON Parser 6
    Google Map JSON Parser Developer Guide
  • Cloud Security for Business 7
    Cloud Security for Business Guest posts
  • The Open Source OS Linux 8
    The Open Source OS Linux Developer Guide
  • Best Headless CMS examples
    Top 5 Best Headless CMS in 2022 Developer Guide
  • ADD AWS Transcribe to Spring Boot APP Tekraze
    Add AWS Transcribe to Spring boot App Developer Guide

Leave a Reply Cancel reply

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

Webtalk Banner

Advertisements

Read Articles on Our Android App

Get it on Google Play

Subscribe to updates






Posts by Categories

Advertisements

  • A Roadway to Learn Web Designing and Development 9
    A Roadway to Learn Web Designing and Development Web Guide
  • The right Way to code and syntax tekraze
    The right way to Code and Syntax you need to follow Developer Guide
  • Open Source - All you need to know Right now 10
    Open Source – All you need to know Right now Developer Guide
  • The Open Source OS Linux 11
    The Open Source OS Linux Developer Guide
  • Linux Terminology basics you need to know
    Git Elements – Post 2 Git and GitHub
  • Photoshop Basics Tutorials 12
    Photoshop Basics Tutorials Web Guide
  • eBook Reader Apps for Android Devices Banner
    Top 5 eBook Reader Apps for Android Devices Android Guide
  • Why Python Programming? 13
    Why Python Programming? Uncategorized

Affliate Links

Earn With Flyout

Earn with Magenet

Sell and Buy with Adsy

GainRock affiliate Program

BloggerOutreach.com

Automatic Backlinks

Encatena - Your content marketing platform
accessily tekraze verificationIndian Blog DirectoryActive Search ResultsLinksBull Directory

Copyright © 2022 Tekraze.

Powered by PressBook News WordPress theme

Advertisements