Walkthrough using Python & Flask to implement restful Web APIs

Source: Internet
Author: User
Here is an example of using Python & Flask to implement a restful Web API. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.

Environment Installation:

sudo pip install flask

Flask is a Python microservices framework based on Werkzeug, a WSGI class library.

Flask Advantages:

Written in Python (that can is an advantage);
Simple-to-use;
Flexible;
multiple good deployment options;
RESTful Request Dispatching

RESOURCES

An API service that responds to/articles and/articles/:id:


From flask import flask, Url_forapp = Flask (__name__) @app. Route ('/') def api_root (): Return ' Welcome ' @app. Route ('/ Articles ') def api_articles (): Return ' List of ' + url_for (' api_articles ') @app. Route ('/articles/<articleid> ') def Api_article (ArticleID): Return ' you are reading ' + articleidif __name__ = = ' __main__ ': App.run ()

Request:

Curl Http://127.0.0.1:5000/

Response:

GET/
Welcome

Get/articles
List Of/articles

Get/articles/123
Reading 123

Requests

GET Parameters


From flask import request@app.route ('/hello ') def api_hello (): If ' name ' in Request.args:  return ' Hello ' + request.arg s[' name '] Else:  return ' Hello John Doe '

Request:

Get/hello
Hello John Doe

Get/hello?name=luis
Hello Luis

Request Methods (HTTP Verbs)


@app. Route ('/echo ', methods = [' Get ', ' POST ', ' PATCH ', ' PUT ', ' DELETE ']) def api_echo (): if Request.method = = ' Get ':  re Turn "echo:get\n" elif request.method = = ' POST ':  return "echo:post\n" elif request.method = = ' PATCH ':  return "EC ho:pacth\n "elif Request.method = = ' PUT ':  return" echo:put\n "elif request.method = = ' DELETE ':  return" Echo:del ETE "

Request specifies the requested type:

Curl-x PATCH Http://127.0.0.1:5000/echo
Get/echo
Echo:get

Post/echo
Echo:post

Request Data & Headers


From flask import json@app.route ('/messages ', methods = [' POST ']) def api_message (): If request.headers[' content-type '] = = ' Text/plain ':  return "text Message:" + request.data elif request.headers[' content-type '] = = ' Application/json ': C3/>return "JSON Message:" + json.dumps (Request.json) elif request.headers[' content-type '] = = ' application/ Octet-stream ':  f = open ('./binary ', ' WB ')  f.write (request.data)    f.close ()  return "binary message written! "Else:  return" 415 unsupported Media Type;) "

Request to specify content type:

Curl-h "Content-type:application/json" \
-X POST http://127.0.0.1:5000/messages-d ' {"message": "Hello Data"} '

Curl-h "Content-type:application/octet-stream" \
-X POST http://127.0.0.1:5000/messages--data-binary @message. bin

Responses


From flask import response@app.route ('/hello ', methods = [' GET ']) def Api_hello (): data = {  ' hello ': ' World ',  ' num ' ber ': 3} js = json.dumps (data) resp = Response (js, status=200, mimetype= ' Application/json ') resp.headers[' Link '] = ' http ://luisrei.com ' return resp

View Response HTTP Headers:

Curl-i Http://127.0.0.1:5000/hello

Optimized code:

From flask Import Jsonify

Use


RESP = jsonify (data) Resp.status_code = 200

Replace


RESP = Response (js, status=200, mimetype= ' Application/json ')

Status Codes & Errors


@app. ErrorHandler (404) def not_found (error=none): message = {   ' status ': 404,   ' message ': ' Not found: ' + Request.url,} resp = jsonify (message) Resp.status_code = 404 Return Resp@app.route ('/users/<userid> ', methods = [' G ET ']) def api_users (userid): users = {' 1 ': ' John ', ' 2 ': ' Steve ', ' 3 ': ' Bill '}  if userid in users:  return jsonify ({ Userid:users[userid]}) Else:  return Not_found ()

Request:

Get/users/2
http/1.0 OK
{
"2": "Steve"
}

Get/users/4
http/1.0 404 Not FOUND
{
"Status": 404,
"Message": "Not FOUND:HTTP://127.0.0.1:5000/USERS/4"
}

AUTHORIZATION


From Functools import wrapsdef check_auth (username, password): return username = = ' admin ' and password = = ' secret ' def Auth Enticate (): message = {' message ': ' Authenticate. '} RESP = jsonify (message) Resp.status_code = 401 resp.headers[' www-authe  Nticate '] = ' Basic realm= ' Example ' return respdef Requires_auth (f): @wraps (f) def decorated (*args, **kwargs):  auth = Request.authorization  if not auth:    return Authenticate ()  elif not Check_auth (Auth.username, Auth.password): Return   Authenticate ()  return F (*args, **kwargs) return decorated

Replacing the Check_auth function and using the Requires_auth decorator:

@app. Route ('/secrets ')
@requires_auth
Def Api_hello ():
Return "Shhh This is top secret spy stuff!"
HTTP Basic Authentication:

Curl-v-U "Admin:secret" Http://127.0.0.1:5000/secrets

Simple DEBUG & LOGGING

Debug:

App.run (Debug=true)
Logging:


Import Loggingfile_handler = logging. Filehandler (' App.log ') App.logger.addHandler (File_handler) app.logger.setLevel (logging.info) @app. Route ('/hello ', methods = [' GET ']) def Api_hello (): App.logger.info (' informing ') app.logger.warning (' Warning ') app.logger.error (' Screaming Bloody murder! ')  Return "Check your logs\n"
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.