Python REST API Tutorial

One of the fundamental characteristics of the modern landscape of development is the clutter-free interface by which REST APIs (Representational State of Transfer Application Programming Interfaces) enable communications between different software systems. It also lets developers create robust applications and facilitates the exchange of data both at the server and client level.

In this course, you are going to learn how to create a REST API with Python so that you can apply it in your very own projects.

What is a REST API?

REST API is the architectural style for designing a web service based on a set of constraints. These APIs rely on the use of standard HTTP methods like GET, POST, PUT, and DELETE while accessing resources on the server. The calls in REST are stateless, which means any call does not communicate with any other call that might have been made. This architecture therefore gives REST APIs the ability to be very scalable, very flexible, and easy to use.

Set Up Your Python Environment

Before you begin building your REST API, you will need to set up your environment. Here’s how to get started:

Installation of Python: If you haven’t installed Python yet, go to the official website for Python to find the most recent edition. We make use of Python 3.7 or higher for the development of an API.

Installing Flask: Flask is one of the most popular, lightweight web frameworks for writing REST APIs in Python. Open your terminal or command prompt and enter the following code lines
pip install

Flask Installing Flask-RESTful: This is an extension, which enables you to build a REST API by extending useful tools for Flask. It can be installed using the following command.
pip install flask-restful

Create your project directory. Instruct your project to make a new directory where your API files are going to reside. Name it with something relevant to your project, “rest_api_project.”

As it comes to Python coding then, Python code can be compiled using online compilers that are similar to the Python Online Compiler.

Building a Simple REST API with Flask

You have created your environment. Let’s now create a simple REST API; we’re going to build an API that we’ll permit to do CRUD operations on a collection of books, each book carrying a title and author. Do the following for now:

Step 1: Setting up the Flask App

Create a new file called app.py in your project directory. In that file, import Flask and Flask-RESTful which essentially sets up a basic Flask app:
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)

Step 2: Defining the Book Resource

Now let’s create a Resource for the books. In Flask-RESTful, a resource is just something which you can treat from your API. So in our application each book is a resource with attributes as title and author. We must now create a class that will map all actions (GET, POST, PUT, DELETE) on books.

To Kill a Mockingbird
Harper Lee
]def get(self, book_id=None):
if book_id:
for book in self.books:
if book[‘id’] == book_id:
return book, 200
return {‘message’: ‘Book not found’}, 404
return self.books, 200

Step 3: Routes and Endpoints Definition

Now, we have to define routes and endpoints for our API. In such a way, our API will be able to handle any different number of routes. For example, it is possible to fetch all books using /books and fetch one book by using its id with the endpoint

/books/<book_id>.
api.add_resource(Book, ‘/books’, ‘/books/<int:book_id>’)

Here, we define two endpoints:/books: This endpoint gives back all the books.
/books/<book_id>: This is the endpoint which gives back details of a book by its ID

Step 4: Adding POST, PUT and DELETE Methods

We will finally add methods that are meant to add new books (POST), update existing books (PUT), and delete books (DELETE).

from flask import request
class Book(Resource):
books = [“]]}
{‘id’: 1, ‘title’: ‘1984’, ‘author’: ‘George Orwell’}
{‘id’: 2, ‘title’: ‘To Kill a Mockingbird’, ‘author’: ‘Harper Lee’}
]def get(self, book_id=None):
if book_id:
for book in self.books:
if book[‘id’] == book_id:
return book, 200
return {‘message’: ‘Book not found’}, 404
return self.books, 200

def post(self):
new_book = request.get_json()
new_book[‘id’] = len(self.books) + 1
self.books.append(new_book)
return new_book, 201

 

def put(self, book_id):
data = request.get_json()
for book in self.books:
if book[‘id’] == book_id:
book.update(data)
return book, 200
return {‘message’: ‘Book not found’}, 404

def delete(self, book_id):
for book in self.books:
if book[‘id’] == book_id:
self.books.remove(book)
return {‘message’: ‘Book deleted’}, 200
return {‘message’: ‘Book not found’}, 404
So, with this, our API supports:

POST: Add a new book.
PUT: Update an existing book by ID.
DELETE: Remove a book by ID.
Step 5: Running the Flask App
And to run your API, add the following lines of code to the bottom of your app.py file:
if __name__ == ‘__main__’:
app.run(debug=True)

Change into your project directory in the terminal and run your app:

python app.py

Your REST API should be now running on http://127.0.0.1:5000. You should use something like Postman or cURL to test it.
Testing Your REST API

Once you’ve developed your API, it’s fairly important to test the API for what you expect. Here’s how you’ll test each method:

GET /books: Fetch all books.
curl http://127.0.0.1:5000/books
GET /books/<book_id>: Fetch a book by ID.
curl http://127.0.0.1:5000/books/1
POST /books: Add new book.
curl -X POST -H “Content-Type: application/json” -d “{\”title\”:\”Brave New World\”,\”author\”:\”Aldous Huxley\”} “”http://127.0.0.1:5000/books
PUT /books/<book_id>: Update a book by ID.
curl -X PUT -H “Content-Type: application/json” -d “{\”title\”:\”Animal Farm\”, “author\”:\”George Orwell\”}””http://127.0.0.1:5000/books/1
DELETE /books/<book_id>: Removes a book by ID.

curl -X DELETE http://127.0.0.1:5000/books/1

Checkout: Digital Marketing in Las Vegas: Unlocking Growth for Local Brands

Conclusion

Building a REST API with Python is very easy if powerful frameworks like Flask and Flask-RESTful exist. In this post you learned step-by-step how to design a simple API handling CRUD operations for a collection of books. From now on, you will keep building even more complex applications that you can base from this foundation such as authentication and pagination. Play around in your API now to unlock the real power of RESTful architecture in your projects.

Leave a Comment