Python simple api server

How to create a simple REST API with Python and Flask in 5 minutes

To make it easier and more convenient, I prepared a video version of this tutorial for those who prefer learning from the movies.

1. Installing Flask and Flask_RESTful

In the beginning, we have to install all the required libraries. Flask is a microframework written in Python, used to build web apps. So, let’s use the following command to install it:

If it’s ready, we can start installing the flask library Flask_RESTful:

If it’s done, we are ready to start building our API!

2. Create and initialize the file

When we installed everything necessary for creating our API, let’s create a file. I’ll call it api.py, and you can use any name you prefer, but remember that Python files should have .py extension. Please open the file in your favorite code editor, and let’s import a few things which are necessary to start our project.

from flask import Flask from flask_restful import Resource, Api, reqparse 

While everything is essential in the top of our file, let’s initialize our API with the following code:

app = Flask(__name__) api = Api(app) STUDENTS = <> if __name__ == "__main__": app.run(debug=True) 

Great, now our API is initialized. Let’s go to the next point where we are going to create our mocked data.

Читайте также:  Exception in thread main java lang noclassdeffounderror com google common collect immutablemap

3. Mocked data

Inside the STUDENTS variable, we are going to create a dictionary of students ordered by id. Every student will have a name, age, and spec property. Let’s create four simple users:

STUDENTS =  '1': 'name': 'Mark', 'age': 23, 'spec': 'math'>, '2': 'name': 'Jane', 'age': 20, 'spec': 'biology'>, '3': 'name': 'Peter', 'age': 21, 'spec': 'history'>, '4': 'name': 'Kate', 'age': 22, 'spec': 'science'>, > 

It’s ready, so we can move one step ahead and start creating our first class with a route.

4. Create StudentsList class and route

Now we can start doing interesting stuff. In the beginning, let’s create a class StudentsList and two methods inside it: get and post.

class StudentsList(Resource): def get(self); def post(self): 

And when it’s ready, we should add a route that will be used as an URL to call the data from this class.

api.add_resource(StudentsList, '/students/') 

Great, now we are almost ready to display our firs data from the endpoint, the last thing which left is to fill in the methods with some logic and run the first endpoints.

5. Create get() and post() methods for StudentsList()

This is a straightforward step. In the first get method of our API, we would like to return a list of all students. To do this, we are going to return our dictionary:

def get(self): return STUDENTS 

Great, now it’s the time to create a post() method to have a possibility to add a new student to our list. For this, we need to create a parser variable just above the class StudentsList to be able to add params to our post() call, and later we can build a post method, where we generate new id and save new student based on passed arguments.

parser = reqparse.RequestParser() 
def post(self): parser.add_argument("name") parser.add_argument("age") parser.add_argument("spec") args = parser.parse_args() student_id = int(max(STUDENTS.keys())) + 1 student_id = '%i' % student_id STUDENTS[student_id] =  "name": args["name"], "age": args["age"], "spec": args["spec"], > return STUDENTS[student_id], 201 

Now, we are ready to check the first calls to our API. First, let’s run the code. I will do it from my code editor. While the code is running you should see the following image in the console:

Duomly - Programming Online Courses

Then, please go the Postman and set the GET method, paste the localhost like where our server works and pass the route at the end. In my case link looks like follows:

The result should display the full list of the students:

Duomly - Programming Online Course

Let’s also check if the post method works as well. For this, you have to change the method to POST, and pass the arguments: name, age, and spec:

Duomly - Programming Online Course

It looks like everything works great! Now it’s time to create another class and other endpoints.

6. Define Student class and route

Now we will create another class and route for that class. The Student class will manage get, update, and delete. Everything in this class concerns a single student got by student_id.

class Student(Resource): def get(self, student_id): def put(self, student_id): def delete(self, student_id): 

Next, we are going to add a new route below the current one:

api.add_resource(Student, '/students/') 

7. Create get(), update() and delete() methods

In this step we will create a logic for get(), update() and delete() methods. First, we would like to return a single student by student_id. Let’s do it:

def get(self, student_id): if student_id not in STUDENTS: return "Not found", 404 else: return STUDENTS[student_id] 

Great, next we will create the update() method logic. It will be very similar to the post() method from the previous class, but we won’t create the new id. First, we are going to check if the student with the given id exists. If yes, we will update the values; if no, we will return the information.

def put(self, student_id): parser.add_argument("name") parser.add_argument("age") parser.add_argument("spec") args = parser.parse_args() if student_id not in STUDENTS: return "Record not found", 404 else: student = STUDENTS[student_id] student["name"] = args["name"] if args["name"] is not None else student["name"] student["age"] = args["age"] if args["age"] is not None else student["age"] student["spec"] = args["spec"] if args["spec"] is not None else student["spec"] return student, 200 

And as the last thing, we will create a delete() method. In this case, we also have to check if the student with the given id exists to be able to delete the item.

def delete(self, student_id): if student_id not in STUDENTS: return "Not found", 404 else: del STUDENTS[student_id] return '', 204 

It seems like everything is ready! Let’s check it!

8. Testing the endpoints

Let’s run our code and open the Postman to be able to test the endpoints. Let’s start by getting a single student. For this we have to pass the link with user id at the end:

Duomly - Programming Online Courses

It works! Let’s try to update the student, set the PUT method, pass the link with the user id, and add some parameter to change them:

Duomly - Programming Online Courses

This one works as well! The last thing to check is delete method. So, let’s create a link with student id at the end and change the method to DELETE:

Duomly - Programming Online Courses

Everything works correctly!

Conclusion

In this article, we created a simple rest API with Python. We used the Flask framework and Flask_RESTful library to make it fast and easy. Our API allows us to get the list of all items, get one item by id, add a new item to the list, update item by id, and delete an item with the given id. For testing the endpoints, I used Postman. To write and run the code, I used the Visual Studio Code.

I hope you will find this tutorial helpful and use it as a base for your first Python API training! If you would like to master your Python knowledge, join Duomly and complete our renewed Python course!

Duomly - Programming Online Courses

Have a nice coding!
Anna from Duomly

Источник

Simple Flask API Server For Beginners — With Sample Code

Hello Coders! This article presents a simple API starter that might help beginners to understand better the API concept. The codebase can be downloaded from Github and used for eLearning activities or production. The framework that powers the API is Flask, a leading software library actively supported and versioned by many open-source enthusiasts.

  • 👉 Simple API over a minimal Datas table
  • 👉 SQLite Persistence managed by an elegant ORM (SqlAlchemy)
  • 👉 Powerful API core provided by Flask-RestX
  • 👉 Strong Input validation
  • 🎁 Free support via email and Discord (1k+ community).
Route Verb Info Status
/datas GET return all items ✔️
POST create a new item ✔️
/datas:id GET return one item ✔️
PUT update item ✔️
DELETE delete item ✔️
  • Flask for routing and overall management
  • Flask-RestX for API
  • Flask-SqlAlchemy — manages the DB with minimal code
  • Docker set up provides a quick start for lazy devs (like me)

✨ API Coding & Implementation Rules

  • Simple Interface
  • Consistent, intuitive actions
  • Use the right verbs for each action
    • GET for read-only actions
    • DELETE for item removal
    • POST for updates

    ✨ Codebase Structure

    All relevant files are listed below. Other files like docker-compose.yml , README, LICENSE are omitted.

    api-server-flask/ ├── api │ ├── __init__.py │ ├── config.py │ ├── models.py │ └── routes.py ├── README.md ├── requirements.txt └── run.py 

    A few words about each one:

    • run.py — the entry point
    • api folder
      • __init__.py constructs the APP
      • models.py — define a single (simple) model
      • routes.py — does the hard work
      • config.py — implements a minimal set up

      ✨ API Models

      The information managed by the API is saved using a simple table defined with three fields: id , data , date_created . Here is the source code:

      # Contents of "api/models.py" (truncated) . class Datas(db.Model): id = db.Column(db.Integer() , primary_key=True) data = db.Column(db.String(256) , nullable=False) date_created = db.Column(db.DateTime() , default=datetime.utcnow) . 

      The source code provides a few helpers that make our life, as a developer, easier:

      • update_data — update the data field
      • save — save & commit the updates of the current object
      • toJSON — returns the JSON representation

      ✨ Routing

      Each method is kept as simple as possible but at the same time, provide a robust validation and elegant SQL access.

      For instance the route that manages the update operation for an item :

      # Contents of "api/routes.py" (truncated) . @rest_api.route('/api/datas/') class ItemManager(Resource): . """ Update Item """ @rest_api.expect(update_model, validate=True) def put(self, id): item = Datas.get_by_id(id) # Read ALL input from body req_data = request.get_json() # Get the information item_data = req_data.get("data") if not item: return "success": False, "msg": "Item not found.">, 400 item.update_data(item_data) item.save() return "success" : True, "msg" : "Item [" +str(id)+ "] successfully updated", "data" : item.toJSON()>, 200 . 

      Let’s iterate over the relevant lines:

      Flask will route the request to this section when user access /api/datas/1 for instance .

      This decorator trigger a validation previously defined as bellow:

      update_model = rest_api.model('UpdateModel', "data": fields.String(required=True, min_length=1, max_length=255)>) 

      If the data field has a size over 255, the request is rejected. For us, as developers, the coding effort is minimal.

      The next steps performed by our handler are:

      • Select the Item from DB using the ID
        • item = Datas.get_by_id(id) via SQLAlchemy
        • Update the data field
        • Save the new object in database

        ✨ Where to go from here

        This simple API will be extended with more features soon:

        • Add more fields to Datas model
        • Implement authentication
        • restrict update actions to authenticated users.

        Have an idea? Please mention your suggestion in the comments section.

        ✨ For more resources, feel free to access:

        Источник

Оцените статью