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

in instablurt •  3 years ago 

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

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.


Cross posted from https://tekraze.com/simple-script-create-rest-api-in-python/



You can support me by giving a vote to my Blurt Witness as I am doing dev work, Hosting an RPC, and now frontend.
If you really want me to be here on this platform, only your witness vote can help me, so feel free to do this by clicking on the below link
https://blurtwallet.com/~witnesses?highlight=tekraze


Follow me on my social networks


Tekraze Blog
Instagram Personal
Instagram Blog account
Instagram Gaming Account
Youtube Gaming
DTube
Tekraze on Medium
Dehazelabs on Medium
Dev.to
Hashnode
Noise
Hive
Steemit
Serey

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!
Sort Order:  
  ·  3 years ago  ·  

This post is published on latest Blurt News post...

Follow us for more news..

  ·  3 years ago  ·  

Thanks

Congratulations, your post has been curated by @dsc-r2cornell. Also, find us on Discord

Manually curated by @abiga554

logo3 Discord.png

Felicitaciones, su publication ha sido votado por @dsc-r2cornell. También, encuéntranos en Discord

  ·  3 years ago  ·  

Thanks

Important information!