Simple rest api python flask

Simple rest api python flask

If you’re coming from front end, you may have gotten used to using JavaScript. This means you could be looking for an alternative to Python, in that case, you might want to check out NodeJS.

and also check out my article similar to this one but focused on NodeJS.

The rest of the article will be covered in Python.

To set up a Python server, you need to install Python, I would suggest any version above 3.7 as of the year 2019.

Once installed, open up your terminal or cmd to install flask.

> pip install Flask
// or
> py -m pip install Flask

Once flask is installed, we’ll need to set up a virtual environment to run our application.

Setting up a Virtual Environment.

We’ll start by creating a folder and adding a venv folder within.

> md sandbox
> cd sandbox
> py -m venv venv

To activate the environment, navigate to ./venv/Scripts/ and on Linux . venv/bin/activate. On windows, use cmd.

./code/sandbox/venv/Scripts/> activate

Navigate back to sandbox which is root and create a file app.py.

Create a minimal Flask application.

Here, we import Flask class and create an instance of it. To create an instance, we’d have to give it a name and using (__name__) ensures that it can be started as an application or imported as a module. We the use the route() decorator to let our flask app know which URL should trigger the corresponding method. The function then simply returns a string message using different URLs in the example.

To run the appliaction, we have to complete a few things first. First, set the environment to development and tell your terminal the application to work with by exporting the FLASK_APP environment variable in Linux.

$ export FLASK_ENV=development
$ export FLASK_APP=app.py

and windows.

> set FLASK_ENV=development
> set FLASK_APP=app.py

Run using.

> flask run
// or
> py -m flask run
* Running on http://127.0.0.1:5000

By default, the port is 5000.

You’ve successfully created your first Python server using Flask. It’s quite basic and returns string responses, let’s spice things up a little by learning some more things we can do.

Routing.

Routes are considered to be endpoints, you can create different routes for your endpoints that use different methods.

We use the route() decorator to bind a function to a URL. Here’s a number of routes with details in the comments.

By default, a route only answers to GET requests. You’ll have to import request from flask to identify the type of method used.

Rendering Templates.

When using express.js, Pug is the default template engine. Well, in Flask we use Jinja2. Flask configures Jinja2 automatically when installing, and to render templates all you would need is to import render_template from flask and variables you would want to pass to the template engine as keyword arguments.

You can learn more about Jinja2 here.

Accessing Request Data.

You might want to pass data via the more secure POST method as opposed to exposing it via the URL. To access form data (transmitted via POST or PUT methods), you can use the form attribute.

If the keys username or password does not exist, then a special KeyError is raised. You can catch it like any other error but if you don’t do that, a HTTP 400 (Bad Request) error page is shown. To access parameters submitted in the URL ( ?key=value ) you can use the args attribute.

searchkeyword = request.args.get('key': '')

It’s recommended to catch KeyError when using URL parameters as some users can change the URL which may return a Bad Request error page.

File Uploads.

Python is a very simple language, it gets even simpler using Flask to upload images, files or videos. Flask allows you to upload files from a form object, just make sure you set enctype="multipart/form-data" attibute on your form.

While uploaded files are temporalily stored in memory or at a temporary location in the file system, you can use the save() method to store the file in the server file system. When you create a server, it’s not recommended you store files on the server, you should store files to a service like AWS Storage, Firebase (by Google), Azure (Microsoft), Dropbox and others and only keep the url to these files stored in a separate database as strings, maybe even in the server. However, here’s how you can save files on the server just incase you just want to.

You can access your file using the hostname of your server plus the file directory i.e https://myapp.com/var/www/uploads/profilephoto.png after saving to the file system.

Conclusion.

It’s pretty easy to build APIs with Flask. You can respond with JSON by serializing the value into JSON and returning it. Use the json module that comes with python to serialize your data into JSON. You can connect to MongoDB and store values using the popular pymongo, or connect to any other database. SQLite3 comes by default in Python. It’s not recommended to use an SQLite database however as your application scales, it’s not powerful enough to handle a lot of data.

If you’re interested more in learning how to connect to databases and store data or upload files to storage services you might want to follow me 😄. Hopefully, you can now set up your own custom REST APIs using Flask. Thanks for going through this article, don’t forget to leave a few claps if you like it 😉.

How do I create a simple REST API with Python and Flask?

CONTENTS.
Install Flask..
Create the List Endpoint in Flask..
Create the Detail Endpoint in Flask..
Add Filters to the List Endpoint..
Build a Create Endpoint..
Create the Update Endpoint..
Create the Delete Record Endpoint..

Is Python Flask a REST API?

"Flask allows Python developers to create lightweight RESTful APIs."

How do I create a simple REST API in Python?

Once installed, open up your terminal or cmd to install flask..
> pip install Flask. // or. ... .
> md sandbox. > cd sandbox. ... .
./code/sandbox/venv/Scripts/> activate..
$ export FLASK_ENV=development. $ export FLASK_APP=app.py..
> set FLASK_ENV=development. > set FLASK_APP=app.py..
> flask run. ... .
searchkeyword = request.args.get('key': '').

How do you write an API in Python Flask?

Minimal Flask App. from flask import Flaskapp = Flask(__name__)@app.route('/hello/', methods=['GET', 'POST']) ... .
Variable Rules. You can add variable sections to a URL by using . ... .
Return JSON Serializable Output. ... .
Redirection Behaviour. ... .
Return Status Code. ... .
Before Request. ... .
Accessing Request Data. ... .
Blueprints..