Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Python API Development Fundamentals
Python API Development Fundamentals

Python API Development Fundamentals: Develop a full-stack web application with Python and Flask

Arrow left icon
Profile Icon Chan Profile Icon Chan Profile Icon Ray Chung Profile Icon Jack Huang
Arrow right icon
₹2904.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (7 Ratings)
Paperback Nov 2019 372 pages 1st Edition
eBook
₹799.99 ₹2323.99
Paperback
₹2904.99
Subscription
Free Trial
Renews at ₹800p/m
Arrow left icon
Profile Icon Chan Profile Icon Chan Profile Icon Ray Chung Profile Icon Jack Huang
Arrow right icon
₹2904.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (7 Ratings)
Paperback Nov 2019 372 pages 1st Edition
eBook
₹799.99 ₹2323.99
Paperback
₹2904.99
Subscription
Free Trial
Renews at ₹800p/m
eBook
₹799.99 ₹2323.99
Paperback
₹2904.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Python API Development Fundamentals

2. Starting to Build Our Project

Learning Objectives

By the end of this chapter, you will be able to:

  • Build a Restful API service efficiently using the Flask-Restful package
  • Build an extendable Flask project
  • Perform CRUD operations using the model
  • Test RESTful APIs using curl, httpie, and Postman

In this chapter, we will start to work on the food recipe-sharing platform and learn how to create a RESTful API application.

Introduction

Now that we've introduced APIs and learned a bit about HTTP and REST, we will work on building an application (the recipe-sharing app known as Smilecook). In this chapter, we aim to kick-start the actual project development. This is a recipe-sharing platform in which users can create accounts and share their own recipes with other users. As you can imagine, it will contain a lot of API endpoints for our users so that they can manage their recipes. We will be using the Flask-RESTful package to efficiently develop our RESTful API.

This chapter will talk about the CRUD (Create, Read, Update, Delete) of these recipes, as well as how to set the publish status of the recipe.

What is Flask-RESTful?

Flask-RESTful is a Flask extension that allows us to quickly develop RESTful APIs. Compared to the built-in wrapper, @app.route('/'), which we discussed in the previous chapter, Flask-RESTful allows us to maintain and structure the API endpoints in a much better and easier way.

In this chapter, we will develop our project using this Flask extension so that you will see how we can structure our endpoints.

Using Flask-RESTful to Develop Our Recipe-Sharing Platform, "Smilecook"

In this book, we are going to develop a recipe-sharing platform called Smilecook. Beginning with this chapter, we will start adding functions to it. We believe this approach will help you learn about the key concepts and skills you will need so that you can develop this application and help it reach its full potential, while at the same time helping you understand the entire development workflow.

First, we will build the basic CRUD functions of the recipes...

Virtual Environment

PyCharm will help us create a virtual environment. We want to develop our project in its own virtual environment in order to keep it isolated. Due to this, we will have absolute control over the versions of the packages that we are going to use.

The best way to learn is through practice. Let's get our hands dirty now!

Exercise 5: Creating a Development Project in PyCharm

Before you start developing the Python application, you'll need to create a development project in PyCharm. PyCharm manages things using projects. In this exercise, you will learn how to create a new development project in PyCharm called Smilecook. You will also need to install the necessary packages for this project. Let's get started:

  1. Create the project and name it smilecook:
    Figure 2.2: Creating a project
  2. Check the project structure and ensure that the virtual environment has been created. Once the module has been created, we will be able to see the project...

Creating a Recipe Model

As you can imagine, a recipe may have several attributes. To save every detail of these attributes, we will model the recipe using a class. This recipe class is going to have several essential attributes.

Here is a brief description of the attributes that we will define in the recipe class:

  • name: The name of the recipe.
  • description: The description of the recipe.
  • num_of_servings: The number of servings.
  • cook_time: The cooking time required. This is an integer whose units are in seconds.
  • directions: The directions.
  • is_publish: The publish status of the recipe; the default is draft.

In the next exercise, we will show you how to code the recipe class so that it has these attributes.

Exercise 6: Creating the Recipe Model

In this exercise, we will code the recipe model, step by step. The recipe class will contain the attributes that we discussed previously. The code file for this exercise can be found in Lesson2/Exercise06...

Configuring Endpoints

Now that we have defined all our resources, we will set up some endpoints so that users can send requests to them. These endpoints can be accessed by the users and are connected to specific resources. We will be using the add_resource method on the API object to specify the URL for these endpoints and route the client HTTP request to our resources.

For example, the api.add_resource(RecipeListResource, '/recipes') syntax is used to link the route (relative URL path) to RecipeListResource so that HTTP requests will be directed to this resource. Depending on the HTTP verb (for example, GET, and POST), the request will be handled by the corresponding methods in the resource accordingly.

Exercise 10: Creating the Main Application File

In this exercise, we will create our app.py file, which will be our main application file. We will set up Flask and initialize our flask_restful.API there. Finally, we will set up the endpoints so that users can send...

Making HTTP Requests to the Flask API using curl and httpie

Now, we are going to use the httpie and curl commands to test our API endpoints. We will test the functions for getting all the recipes back from the server and create/update/delete, publish, and unpublish the recipes. The best way to learn this is to complete a hands-on exercise. Let's get started!

Exercise 11: Testing the Endpoints Using curl and httpie

In this exercise, we are going to use the httpie and curl commands to send requests to the endpoints so that we can create our first recipe. We want you to get comfortable using the httpie and curl command-line testing tool. Let's get started:

  1. Open the Terminal in PyCharm and type in the following commands. You can use either the httpie or curl command. The following is the httpie command (= is for string and := is for non-string):
    http POST localhost:5000/recipes name="Cheese Pizza" description="This is a lovely cheese pizza" num_of_servings...

Summary

In this chapter, we built the RESTful API using the Flask-RESTful package. By doing this, you have seen how simple and easy it is to perform such tasks. We are building our project in a structural manner, which allows us to easily extend the project in the subsequent chapters. In this chapter, we created the models and resources folder; we will be developing more models and resources later in this book. So far, our food recipe-sharing platform, Smilecook, is capable of performing CRUD, as well as setting the publish status of the recipe. We have also tested the application to make sure it is working properly. Finally, you started to realize the power of Postman, which greatly automates the whole testing process. In the next chapter, we will learn about how to perform data validation.

Left arrow icon Right arrow icon

Key benefits

  • Delve deep into the principle behind RESTful API
  • Learn how to build a scalable web application with the RESTful API architecture and Flask framework
  • Know what are the exact tools and methodology to test your applications and how to use them

Description

Python is a flexible language that can be used for much more than just script development. By knowing the Python RESTful APIs work, you can build a powerful backend for web applications and mobile applications using Python. You'll take your first steps by building a simple API and learning how the frontend web interface can communicate with the backend. You'll also learn how to serialize and deserialize objects using the marshmallow library. Then, you'll learn how to authenticate and authorize users using Flask-JWT. You'll also learn how to enhance your APIs by adding useful features, such as email, image upload, searching, and pagination. You'll wrap up the whole book by deploying your APIs to the cloud. By the end of this book, you'll have the confidence and skill to leverage the power of RESTful APIs and Python to build efficient web applications.

Who is this book for?

This book is ideal for aspiring software developers who have a basic-to-intermediate knowledge of Python programming and who want to develop web applications using Python. Knowledge of how web applications work will be beneficial but is not essential.

What you will learn

  • Understand the concept of a RESTful API
  • Build a RESTful API using Flask and the Flask-Restful extension
  • Manipulate a database using Flask-SQLAlchemy and Flask-Migrate
  • Send out plaintext and HTML format emails using the Mailgun API
  • Implement a pagination function using Flask-SQLAlchemy
  • Use caching to improve API performance and efficiently obtain the latest information
  • Deploy an application to Heroku and test it using Postman
Estimated delivery fee Deliver to India

Premium delivery 5 - 8 business days

₹630.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 22, 2019
Length: 372 pages
Edition : 1st
Language : English
ISBN-13 : 9781838983994
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to India

Premium delivery 5 - 8 business days

₹630.95
(Includes tracking information)

Product Details

Publication date : Nov 22, 2019
Length: 372 pages
Edition : 1st
Language : English
ISBN-13 : 9781838983994
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 9,458.97
Hands-On Docker for Microservices with Python
₹3276.99
Python API Development Fundamentals
₹2904.99
Python GUI Programming Cookbook
₹3276.99
Total 9,458.97 Stars icon

Table of Contents

10 Chapters
1. Your First Step Chevron down icon Chevron up icon
2. Starting to Build Our Project Chevron down icon Chevron up icon
3. Manipulating a Database with SQLAlchemy Chevron down icon Chevron up icon
4. Authentication Services and Security with JWT Chevron down icon Chevron up icon
5. Object Serialization with marshmallow Chevron down icon Chevron up icon
6. Email Confirmation Chevron down icon Chevron up icon
7. Working with Images Chevron down icon Chevron up icon
8. Pagination, Searching, and Ordering Chevron down icon Chevron up icon
9. Building More Features Chevron down icon Chevron up icon
10. Deployment Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(7 Ratings)
5 star 14.3%
4 star 14.3%
3 star 28.6%
2 star 42.9%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




TIffany York Dec 03, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have only gotten through the first chapter and I am quite happy with it. I have read a lot regarding APIs but having a book that walked me through the creation of one helped solidify the knowledge. Context: I am a Network Engineer trying to break into network automation.
Amazon Verified review Amazon
Yosef Cohen Jun 15, 2020
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The book is good , but there are small mistakes here and there. There is a problem too that when you upload your app to heroku it don't support uploading images , and I was very disappointed from it.
Amazon Verified review Amazon
Phillip F Norris Jun 23, 2023
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I like that the book provides the necessary ingredients for building a website from scratch, but one of the libraries that it uses extensively has evolved. Of course, I could have used the library versions they use (that are a few years old at this point, if they are still available), but I've wanted to learn the current tech. Until now, I've been able to figure out what needs to change in order to work, like jwt_optional has become jwt_required(optional=True). The internet is not overflowing with those types of corrections, and the library's documentation doesn't connect the dots without effort . At the moment, I have no idea on the current implementation of get_raw_jwt. Would be great if the authors provided updates on their code page.
Amazon Verified review Amazon
Shun-Chi Lo Oct 14, 2020
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I found this book is useful and well structured, but some sample codes have errors. Maybe it's good for debugging practice but can take you some time.
Amazon Verified review Amazon
Anthony K. Jan 27, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I was very excited to receive this book, but when I started reading, I found that most illustrations in the book are blurry! a little bit disappointed!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela