First, create a new folder for your project:
mkdir python-rest-api && cd python-rest-api
Then, create a virtual environment:
python3 -m venv env
Activate the virtual environment:
On macOS and Linux:
source env/bin/activate
On Windows:
.\env\Scripts\activate
Install Flask, Flask-RESTful, SQLAlchemy, Flask-SQLAlchemy, and marshmallow using pip:
pip install flask flask-restful flask-sqlalchemy marshmallow
Create a new file named app.py
:
touch app.py
Open app.py
in your text editor and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
We'll create a simple User
model. Add the following code to app.py
:
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '' % self.username
We'll use marshmallow to serialize and deserialize our User
model. Add the following code to app.py
:
from marshmallow import Schema, fields
class UserSchema(Schema):
id = fields.Int(dump_only=True)
username = fields.Str()
email = fields.Email()
We'll create a UserResource
that will handle HTTP requests. Add the following code to app.py
:
from flask_restful import Resource, Api, request
from marshmallow import ValidationError
api = Api(app)
user_schema = UserSchema()
class UserResource(Resource):
def get(self):
users = User.query.all()
return user_schema.dump(users, many=True)
def post(self):
try:
user = user_schema.load(request.json)
db.session.add(user)
db.session.commit()
return user_schema.dump(user)
except ValidationError as err:
return err.messages, 400
api.add_resource(UserResource, '/users')
You can now test your API. Run your Flask application:
python app.py
You should be able to retrieve and create users by sending HTTP requests to http://localhost:5000/users
.
For a GET
request, you can simply visit the URL in your browser. For a POST
request, you can use a tool like curl or Postman.
Here's an example of a POST
request with curl:
curl -X POST -H "Content-Type: application/json" -d '{"username": "test", "email": "test@example.com"}' http://localhost:5000/users
This is a basic example of a Python REST API. There's a lot more you can do, like adding authentication, handling more types of requests, and adding more resources. But this should give you a good start.