Photo by Ciprian Boiciuc on Unsplash

How to make a simple API for generating random names and emails using Flask.

This article is for the beginner who is looking to create an API using the flask. We will be creating an API that can return a random name and email for every request that reaches the API.

Goals:

  1. Build the application.
  2. Deploying the application.

Install Flask and Faker

pip install flask
pip install Faker
# hello.py
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
return "Hello World!"
$ FLASK_APP=hello.py flask run
* Running on http://localhost:5000/

Part 1. Building the application

To begin, we are going to be using the command line to build out a folder and make files for our application.

$ mkdir flask_api
$ # Make a server file
$ cd flask_api
$ touch server.py
# Import nessecary parts from flask and faker to generate random    # name and email.
from
flask import Flask, request, jsonify
from faker import Faker
# To create and initialize a faker generator.
fake = Faker()
# Create the app object that will route our calls.
app = Flask(__name__)
# Add a single endpoint that we can use as an API to accept GET and # POST requests.
@app.route("/", methods=["POST", "GET"])
def index():
# fake to create random name and email
name = fake.name()
email = fake.email()
response = {
"name": name,
"email": email
}
# return name and email as a JSON httpresponse using jsonify
return jsonify(response)
# When run from command line, start the server.
if
__name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
  1. In a terminal navigate to your flask_api folder
  2. Enter command python server.py to run server
  3. Navigate to http://localhost:5000 in your web browser
  4. You are now running your own server locally!
{
"email": "douglasavery@mcgee.org",
"name": "Anthony Rogers"
}
https://github.com/Joel-hanson/flask_api

Next Steps

We have done the coding part for our application. The continuation parts of this post will be showing you how to deploy this application.

  1. Add your code to GitHub.
  2. Deploy your application to Heroku.

Works at @impressAI