Python flask json api

Python Flask 101 — Intro and API Building

Every programming language has frameworks for building web server, also known as a web framework. In Python, there are several such as Django, Bottle, Pyramid, Masonite, FastAPI, Web2Py and many more. Next to Django, the most heavily used Python web framework is Flask. Flask is the ExpressJS (minimalist web framework) what Django is to Ruby on Rails (Batteries Included Web Framework). In this tutorial we will be building a basic JSON API in flask. Afterwards I’ll share resources for going deeper into using flask.

Pre-Requisites:

Setup

  • Create an empty folder to work out of
  • Open terminal in that folder
  • create a python virtual environment python -m venv venv
  • Turn on the Virtual Environment source ./venv/bin/activate (notice the change in your terminal prompt)

If not familiary with what are and what is the purpose of virtual environments read the following articles

Our First Route

# Import the flask library from flask import Flask # create the flask application object pa app = Flask(__name__) ## Decorator making the subsequent function a route @app.route("/", methods=["GET"]) ## this functions return value is the response of the route (function name doesn't matter) def first_route(): return "hello world", 200 ## will return text with a 200 status 

** If your wondering about the name variable, it’s a special variable in python you can read about here**

To run the server use the command

FLASK_APP=server.py python -m flask run

  • FLASK_APP=server.py This defines the FLASK_APP env variable needed to determine which file has the app object for Flask to run.
  • python -m allows you to run a python module or file as a script
  • Flask we are running the Flask module
  • run the run is a command built into the Flask module to create a web server with the app specified by the FLASK_APP variable

Once the server is running head over to localhost:5000 and you should see hellow world! Congrats, you have created your first flask route!

JSON API BASICS

Returning JSON responses in Flask is pretty easy, as long as the routes function returns a python dictionary it can turned into JSON. For any python class instances you can either convert them into a dictionary by adding a built in as_dict method.

class Dog(): ## Dog Constructor def __init__(self, name, age): self.name = name self.age = age ## Method for Turning to Dictionary to send back as JSON def as_dict(self): return c.name: getattr(self, c.name) for c in self.__table__.columns> ## Create Instance of Dog sparky = Dog("Sparky", 5) ## Print Dog as a Dictionary print(Dog.as_dict()) 

Basic Crud

We will use a basic list/array of meals inside of dictionary to create a simple api to add, edit, delete the meals in the array. Add the following to server.py.

  • notice we added request to the import of Flask, this allows us to pull data from the request like the request body and method
## List of Dictionaries containing meals meals = ["meal": "breakfast">, "meal": "lunch">, "meal": "dinner">] ## INDEX & CREATE ROUTE - Return all meals and create meals @app.route("/meals", methods=["GET", "POST"] ) def meals_index_create(): ## If a get request, return all meals if (request.method == "GET"): print(meals) return "meals": meals> ## If a post, add a meal expecting a json body with a meal property if (request.method == "POST"): # get the request body as a python dictionary body = request.json # append the new meal to meals meals.append(body) # return new list of meals return "meals": meals> 

If you want start the server and use a tool like postman to make a get and post request to /meals. Make sure to send a json body for the post request.

Next we’ll add Show, Delete and Update routes

  • notice the in side the definition of the endpoint. This is called a URL param and is a way to define a variable in the url itself. We can then receive this variable as an argument to our route function (notice now the function has parameters defined).
  • since we will make assignments using the meals variable name, without further detail, python will think we are creating a new «local» version of meals not editing the global one defined outside the function. To access meals we will use the global keyword to declare that references to meals in this function are references to the previously defined global variable.
  • In the delete part you’ll notice some strange syntax, this is called List of Dictionary comprehension. Essentially, it’s a way of creating a new list/dict by looping over another one. Read More. List Comprehension — Dictionary Comprehension
 ## SHOW, Update, and Delete routes - Get one, update one, delete one @app.route("/meals/", methods=["GET", "PUT", "DELETE"]) def meals_show_update_delete(index): # save the contents of the request body body = request.json # make sure that meals refers to the global variable before reassignment global meals # make sure that the index is a integer, not a string index = int(index) if(request.method == "GET"): # return the meal at the index specified in the url param return meals[index] if(request.method == "PUT"): #update the specified index with the request body, then return it meals[index] = body return meals[index] if(request.method == "DELETE"): ## make meals a new dictionary, where the meals list has the desired item removed using the list comprehension feature (creating a list or dict by iterating over another one with an expression) meals =  "meals":[i for i in meals if not (i["meal"] == meals[index]["meal"])] > return meals 

There you have full CRUD on meals, exciting!

What’s next

Источник

Flask REST API Tutorial

REST API services let you interact with the database by simply doing HTTP requests. In this article you learn how to write a REST server using the Flask.

This is often how the backend of web apps is created. Returning data is in JSON format and requests we are using are PUT, DELETE, POST, and GET

If you want to put your API online, use: PythonAnywhere.

Flask API example

Introduction

To make our first program, recall that we enter the URL in the browser

At the time, a string “Hello World!” was returned, so we thought, can we replace this string with a json sequence? Isn’t that the same as a REST query API?

So, we might have the first impulse to do this:

Actually, we just modified the returned string, modified it to a string of JSON, and then we opened it on the browser

flask json

Wow! It seems to have achieved the function we wanted, returned a JSON string.

But we opened the debug tool for Chrome (which I use as a tool similar to Chrome, Safari, Firefox) (under Windows: Ctrl + Alt + I, Mac under: Cmd + Shift + I), we can see that this returned data type actually is of type html:

dev tools content type html

You may wonder what impact this might have, the impact should be small in most cases, but for some mobile-side libraries, the data may be processed according to the response (incorrectly!).

If you want to put your API online, use: PythonAnywhere.

Return json

To deal with this situation, we can’t simply set this response head into json format.
A better solution is to use the jsonify function of the Flask, where I use this function to modify the code:

flask json response

Look at Google Dev Tools, you’ll see the content-type change to JSON.

google developer tools json response

Request method

We know that there are six commonly used HTTP request methods, which are

The code that we just had had to deal with GET by default (the browser defaults to using GET), so how do you program the other requests?

@app.route(‘/’, methods=[‘POST’])
@app.route(‘/’, methods=[‘DELETE’])
@app.route(‘/’, methods=[‘PUT’])

The program below demonstrates this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
# encoding: utf-8
import json
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route(‘/’, methods=[‘GET’])
def query_records():
name = request.args.get(‘name’)
print name
with open(‘/tmp/data.txt’, ‘r’) as f:
data = f.read()
records = json.loads(data)
for record in records:
if record[‘name’] == name:
return jsonify(record)
return jsonify({‘error’: ‘data not found’})

@app.route(‘/’, methods=[‘PUT’])
def create_record():
record = json.loads(request.data)
with open(‘/tmp/data.txt’, ‘r’) as f:
data = f.read()
if not data:
records = [record]
else:
records = json.loads(data)
records.append(record)
with open(‘/tmp/data.txt’, ‘w’) as f:
f.write(json.dumps(records, indent=2))
return jsonify(record)

@app.route(‘/’, methods=[‘POST’])
def update_record():
record = json.loads(request.data)
new_records = []
with open(‘/tmp/data.txt’, ‘r’) as f:
data = f.read()
records = json.loads(data)
for r in records:
if r[‘name’] == record[‘name’]:
r[’email’] = record[’email’]
new_records.append(r)
with open(‘/tmp/data.txt’, ‘w’) as f:
f.write(json.dumps(new_records, indent=2))
return jsonify(record)

@app.route(‘/’, methods=[‘DELETE’])
def delte_record():
record = json.loads(request.data)
new_records = []
with open(‘/tmp/data.txt’, ‘r’) as f:
data = f.read()
records = json.loads(data)
for r in records:
if r[‘name’] == record[‘name’]:
continue
new_records.append(r)
with open(‘/tmp/data.txt’, ‘w’) as f:
f.write(json.dumps(new_records, indent=2))
return jsonify(record)

app.run(debug=True)

The code is long, but the code is easier to understand, and it is a relatively simple file operation.

The code that we need to focus on is the following:

@app.route(‘/’, methods=[‘GET’])
@app.route(‘/’, methods=[‘PUT’])
@app.route(‘/’, methods=[‘POST’])
@app.route(‘/’, methods=[‘DELETE’])

If you want to put your API online, use: PythonAnywhere.

How to Set Up Flask with MongoDB

Источник

Читайте также:  Symfony component httpfoundation request php
Оцените статью