Python Rest

REST API Jumpstart Guide with Python REST web-service Example

REST stands for Representational State Switch.

It’s an architectural type, set of rules to standardize the online, to take care of uniformity across net purposes worldwide. It intends to reinforce maintainability, scalability, reliability and portability of net purposes.

Foremost concept behind REST is assets. Every part you need to entry in an internet software is a useful resource, whether it is a media or documents you need to download, update, delete. REST defines a solution to entry, transfer, and modify these assets.

This tutorial covers the next three high-level concepts:

  • REST Primary Ideas – This part explains the 6 key relaxation architectural constraints
  • Key parts of RESTFul implementation – This part the 6 totally different parts of a RESTful implementation
  • Create a Python REST web-service – This sections provides a step-by-step instruction on making a primary REST web-service in python

REST Primary Ideas

The next are few architectural constraints that may make any net service RESTful, as discussed by Roy Fielding, inventor of REST in his analysis paper.

1. Shopper Server

This constraint states that shopper and server implementation ought to be unbiased, both ought to have the ability to scale, evolve independently of one another. Shopper should only know URI of useful resource on server nothing else. Server should return the suitable response based mostly on acquired request from the shopper.

2. Stateless

Shopper-server interaction ought to be stateless in nature. Server shouldn’t store state knowledge and response ought to completely depend on the knowledge present in the request from shopper. Shopper can nevertheless store maintain session state knowledge. This enhances scalability, reliability of interactions.

3. Cache

Cache comes into the picture to unravel the difficulty of stateless nature of REST. This cache is carried out on shopper finish, and cacheable response is cached. If in future shopper request some knowledge for which it had already despatched a request, as an alternative of sending the request to server again, cache can reuse the cached response.

four. Uniform Interface

This states the necessity of uniform interface between elements, every resource in server ought to have only one logical URI and will expose strategies to entry this resource, and it should comply with normal naming conventions. All useful resource must be accessed utilizing widespread strategy. This enhances visibility of net interfaces.

5. Layered System

Layered system strategy states that net service ought to comply with layered strategy, i.e. we should always divide our net service in several layers that can’t see beyond their speedy layer, e.g. authentication layer, knowledge entry layer, message processor layer. This reduces system complexity and improves scalability.

6. Code on demand

This states that sometimes shopper can obtain executable code as an alternative of static knowledge, i.e. JSON/XML. It will increase system extensibility.

Key Parts of RESTFul implementation

1. Resource

The essential concept behind REST is resource, every little thing stored in REST net service knowledge retailer is a useful resource. In present context articles stored in TGS knowledge store is a useful resource. We will access this resource using URI https://www.thegeekstuff.com/category/python/

2. Request Verbs

These defines the best way to access the assets, what shopper needs to do with them is specified with the request verbs, these are primary strategies

  1. GET: This shall be used to get articles from knowledge store of TGS net software.
  2. POST: This shall be used to create a brand new article in TGS net software.
  3. PUT: This shall be used to replace any present article or create a new if it doesn’t exist in TGS knowledge retailer.
  4. DELETE: This can be used to delete an article from TGS knowledge retailer.

three. Request Headers

Additional request despatched to server to specify sort of response, encoding, and content material sort and customised parameters. And so on.

4. Request Body

When making an attempt to create a resource, the useful resource knowledge is shipped in body of put request.

5. Response Physique

Net server returns knowledge in physique of the response. Suppose shopper despatched a GET to query knowledge for python class, net server will return knowledge in response body.

6 Response Codes

These coded returned with the response, and signifies the standing of the request sent to the server. These just like HTTP response code. E.g. 200 OK denotes request succeeded, 404 NOT FOUND denotes resource not found on server.

Create a Python REST web-service

Let’s create a simple REST net service utilizing flask in python, we might eat this net service using Postman software or Curl command line utility.

In case you are new to Python, seek advice from this: 5 Examples to Jumpstart Object Oriented Programming in Python

Our resource in this service will probably be articles, it’ll store all of the articles revealed on TGS, in following format

We’ll expose REST endpoints to add, modify, delete, and update the articles. CRUD functionality over REST.

Let’s begin step by step:

1. Import Flask Module

First, import flask module inside the code and identify our net service as shown under.

from flask import Flask
from flask_restful import Useful resource, reqparse , api

TGS = Flask(__name__)
api = Api(TGS)

2. Create Resource Articles

Next, create useful resource articles, it is going to be a easy Listing of articles , we will also use a database to store out resource.

articles = [

“category”: “python”,
“views”: 100,
“title”: “Dictionary”
,

“category”: “java”,
“views”: 200,
“title”: “java10”
,

“category”: “elastic”,
“views”: 300,
“title”: “elasticsearch”

]

three. Create API End Points and REST Methods

Subsequent, we have to create the api endpoints and the required REST methods as present under.

GET technique will search requested category in record of articles, and will return the info if discovered along with response code 200 OK. Otherwise 404 not discovered

class Article(Useful resource):
def get(self, class):

POST technique will insert new article knowledge in record of articles and returns inserted knowledge with response code 201 created. If document already exists it returns error code 400 dangerous request.

def submit(self,category):

PUT technique will overwrite the document and return the info along with response code 200 OK. If report doesn’t exist, it creates the info and returns it with response code 201 created.

def put(self,class):

DELETE technique deleted the document if exist and returns the info with response code 200 OK. In any other case 404 not found.

def delete(self,category):

four. Register Useful resource and Assign URI

Our remaining step is registering our resource to REST API and assign a URI to it.

api.add_resource(Article, “/class/“)

TGS.run(debug=True,port=8080)

Full REST Sample Program

Create relaxation.py file:

vi relaxation.py

Copy/paste the next to the remaining.py file:

from flask import Flask
from flask_restful import Useful resource, reqparse ,Api

TGS = Flask(__name__)
api = Api(TGS)

articles = [

“category”: “python”,
“views”: 100,
“title”: “Dictionary”
,

“category”: “java”,
“views”: 200,
“title”: “java10”
,

“category”: “elastic”,
“views”: 300,
“title”: “elasticsearch”

]

class Article(Resource):
def get(self, category):
for article in articles:
if(class == article[“category”]):
return article, 200
return “category not found”, 404

def publish(self, class):
parser = reqparse.RequestParser()
parser.add_argument(“views”)
parser.add_argument(“title”)
args = parser.parse_args()

for article in articles:
if(category == article[“category”]):
return “category already exists”.format(class), 400

article =
“category”: category,
“views”: args[“views”],
“title”: args[“title”]

articles.append(article)
return article, 201

def put(self, class):
parser = reqparse.RequestParser()
parser.add_argument(“views”)
parser.add_argument(“title”)
args = parser.parse_args()

for article in articles:
if(class == article[“category”]):
article[“views”] = args[“views”] article[“title”] = args[“title”] return article, 200

article =
“category”: category,
“views”: args[“views”],
“title”: args[“title”]

articles.append(article)
return article, 201

def delete(self, category):
international articles
articles =[articleforarticleinarticlesifarticle[articleforarticleinarticlesifarticle[articleforarticleinarticlesifarticle[articleforarticleinarticlesifarticle[“category”] != class]return “ is deleted.”.format(category), 200

api.add_resource(Article, “/class/“)

TGS.run(debug=True,port=8080)

Check the REST Program

Let’s check this using Curl utility, we might use postman utility additionally it’s an amazing device.

Start the python glass REST server

$ python rest.py
* Serving Flask app “rest” (lazy loading)
* Setting: production
WARNING: Do not use the event server in a manufacturing setting.
Use a manufacturing WSGI server as an alternative.
* Debug mode: on
* Restarting with stat
* Debugger is lively!
* Debugger PIN: 145-292-899
* Operating on http://127.0.0.1:8080/ (Press CTRL+C to give up)

1. GET articles from python category of TGS

$ curl -XGET http://127.0.0.1:8080/category/python
% Complete % Acquired % Xferd Common Velocity Time Time Time Present
Dload Add Complete Spent Left Velocity
100 74 100 74 0 zero 74000 0 –:–:– –:–:– –:–:– 74000
“category”: “python”,
“views”: 100,
“title”: “Dictionary”

2. POST a brand new category article to TGS

$ curl -XPOST http://127.0.0.1:8080/class/c++ -H “Content-Type: application/json” –knowledge ‘ “category”: “c++”, “views”: “199”, “title”: “tuples” ’
% Complete % Acquired % Xferd Common Velocity Time Time Time Current
Dload Upload Complete Spent Left Velocity
100 125 100 69 100 56 1468 1191 –:–:– –:–:– –:–:– 2659
“category”: “c++”,
“views”: “199”,
“title”: “tuples”

3. PUT an article , modify C++ class article

$ curl -XPUT http://127.0.0.1:8080/class/c++ -H “Content-Type: application/json” –knowledge ‘ “category”: “c++”, “views”: “201”, “title”: “tuples” ’
% Complete % Acquired % Xferd Common Velocity Time Time Time Present
Dload Add Complete Spent Left Velocity
100 125 100 69 100 56 69000 56000 –:–:– –:–:– –:–:– 122okay
“category”: “c++”,
“views”: “201”,
“title”: “tuples”

$ curl -XGET http://127.0.0.1:8080/category/c++
% Complete % Acquired % Xferd Common Velocity Time Time Time Current
Dload Add Complete Spent Left Velocity
100 69 100 69 zero zero 4312 zero –:–:– –:–:– –:–:– 4312
“category”: “c++”,
“views”: “201”,
“title”: “tuples”

As you possibly can see C++ class document is up to date.

four. DELETE an article from C++ category

$ curl -XDELETE http://127.0.0.1:8080/category/c++
% Complete % Acquired % Xferd Average Velocity Time Time Time Present
Dload Add Complete Spent Left Velocity
100 18 100 18 0 zero 18000 zero –:–:– –:–:– –:–:– 18000″c++ is deleted.”

$ curl -XGET http://127.0.0.1:8080/category/c++
% Complete % Acquired % Xferd Average Velocity Time Time Time Current
Dload Add Complete Spent Left Velocity
100 21 100 21 zero zero 21000 zero –:–:– –:–:– –:–:– 21000″class not found”

Really helpful exercise: Use MySQL or any database to retailer articles and implement knowledge entry layer to offer CRUD functionality over REST.

For those who loved this text, you may also like..