Sunday, May 24, 2020

Building REST APIs with FLASK Python Web Services- CRUD Application with FLASK Part-2


So this part will contain the other methods which I mentioned in the first 1st part.let's see GET author endpoint.

@author_routes.route('/',methods=['GET'])
def get_author_list():
    fetched = Author.query.all()
author_schema=AuthorSchema(many=True,only=['first_name','last_name','id'])
authors,error=author_schema.load(fetched)
result=author_schema.dump(fetched)
return response_with(resp.SUCCESS_200,value={"authors": authors})
 
This will GET all authors route and here we will respond with an array of authors only containing their ID, First Name, and Last Name.

So just hit the URL with POSTMAN.

https://localhost:5000/api/authors/


Now lets add another GET route to fetch a specified author using their ID and add the follwiiong code to it add the route:

@author_routes.route('/<int:author_id>',methods=['GET'])
def get_author_detail():
    fetched = Author.query.get_or_404(author_id)
author_schema=AuthorSchema()
author,error=author_schema.load(fetched)
result=author_schema.dump(fetched)
return response_with(resp.SUCCESS_200,value={"author": author})
 
So hit the URL with POSTMAN like 
https://localhost:5000/api/authors/1

Before we move on to creating PUT and DELETE endpoints for author object. let's initiate book routes. Create books.py in the same folder and add the following code to initiate the route.

from flask import Blueprint
from flask import request
from api.responses import response_with
from api import responses as resp
from api.models.authors import Author ,AuthorSchema
from api.databases import db

author_routes = Blueprint("author_routes",_name_)

from api.routes.books import book_routes
app.register_blueprint(book_routes,url_prefix='/api/books')

now to create book use below methods:

@book_routes.route('/',methods=[POST])
def create_book():
    try: 
    data = request.get_json()
book_schema = BookSchema()
book,error = book_schema.load(data)
result = book_schema.dump(book.create()).data
return response_with(resp.SUCCESS_201,value={"book":result})
except Eception as e:
        print e
        return response_with(resp.INVALID_INPUT_422)

To test the method hit the URL with POSTMAN
http://localhost:5000/api/books/

Ans also use below JSON formate to hit.

{
  "title":"Android Book",
  "year":2007,
  "author_id":1
}

So this way you will able to create all the methods that I mentioned in the 1st part. Let me know if any problems.
 

No comments: