# 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](https://tekraze.com/wp-content/uploads/2022/01/A-simple-script-to-create-Rest-API-in-Python-with-Dockerization-as-Bonus-1.png "A simple script to create Rest API in Python with Dockerization as Bonus 9")

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](https://pypi.org/project/falcon/)
2.  [requests Pypi package](https://pypi.org/project/requests/)
3.  Docker
4.  [Gunicorn](https://pypi.org/project/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](https://miro.medium.com/max/722/1*Qw0b65BowIAAoZaFep9dqg.png "A simple script to create Rest API in Python with Dockerization as Bonus 10")

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](https://miro.medium.com/max/573/1*_fyWGUUeVXZhfiyHmZyACg.png "A simple script to create Rest API in Python with Dockerization as Bonus 11")

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](https://miro.medium.com/max/423/1*J4m5G2YBTkFfDTx07qIA0g.png "A simple script to create Rest API in Python with Dockerization as Bonus 12")

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](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/

---

# Follow me on my social networks

* * * * *

[Tekraze Blog](https://tekraze.com/ "This link will take you away from blurt.blog")\

[Instagram Personal](https://instagram.com/balvinder294 "This link will take you away from blurt.blog")\

[Instagram Blog account](https://instagram.com/tekraze786 "This link will take you away from blurt.blog")\

[Instagram Gaming Account](https://instagram.com/tekraze.gaming "This link will take you away from blurt.blog")\

[Youtube Gaming](https://www.youtube.com/channel/UCj4z8phwJn4yCXrtlEYxnVA "This link will take you away from blurt.blog")\

[DTube](https://d.tube/#!/c/tekraze786 "This link will take you away from blurt.blog")\

[Tekraze on Medium](https://medium.com/tekraze "This link will take you away from blurt.blog")\

[Dehazelabs on Medium](https://blog.dehazelabs.com/ "This link will take you away from blurt.blog")\

[Dev.to](https://dev.to/balvinder294 "This link will take you away from blurt.blog")\

[Hashnode](https://tekraze.hashnode.dev/ "This link will take you away from blurt.blog")\

[Noise](https://noise.cash/u/tekraze "This link will take you away from blurt.blog")\

[Hive](https://hive.blog/@balvinder294 "This link will take you away from blurt.blog")\

[Steemit](https://steemit.com/@tekraze "This link will take you away from blurt.blog")

[Serey](https://serey.io/authors/tekraze)

