Python Flask API Examples
Simple API with GET method:
In this example, we define a route that listens for GET requests to the '/hello' endpoint. When a request is received, the 'hello' function is executed, which returns a JSON response containing a 'message' field with the value "Hello, World!".
API that accepts parameters:
In this example, we define a route that listens for GET requests to the '/square' endpoint. The function 'square' retrieves a 'number' parameter from the query string using Flask's 'request.args.get' method. If a valid number is provided, the function calculates its square and returns a JSON response with the result. Otherwise, it returns an error message.
API that accepts JSON data and returns JSON data:
In this example, we define a route that listens for POST requests to the '/reverse' endpoint. The function 'reverse' retrieves the message to reverse from the JSON data using Flask's 'request.json' method. If a valid message is provided, the function reverses it and returns a JSON response with the reversed message. Otherwise, it returns an error message.
API that uploads files:
In this example, we define a route that listens for POST requests to the '/upload' endpoint. The function 'upload' retrieves a file from the request using Flask's 'request.files' method. If a valid file is provided, the function saves it to disk or processes it as needed and returns a JSON response with a success message. Otherwise, it returns an error message.
API that integrates with a database:
In this example, we define a route that listens for GET requests to the '/users' endpoint, which retrieves all the users from the database and returns them as a JSON response. We also define a route that listens for POST requests to the '/users' endpoint, which adds a new user to the database based on the JSON data in the request.
We use Flask-SQLAlchemy to manage the database connections and define the 'User' model. When a new user is added, we create a new 'User' object and add it to the database session, then commit the changes.
API that integrates with external services:
In this example, we define a route that listens for POST requests to the '/translate' endpoint. The function 'translate' retrieves the text to translate and target language from the JSON data using Flask's 'request.json' method. It then sends a request to the Google Translate API to translate the text, and returns a JSON response with the translated text.
API that streams data:
In this example, we define a route that listens for GET requests to the '/stream' endpoint. The function 'stream' generates a stream of data using a generator function, which yields a sequence of numbers from 0 to 9 separated by newlines. It then returns a Flask 'Response' object with the generated data and a mimetype of 'text/plain'.
When a client makes a request to this endpoint, they will receive a stream of data in the response, with each number separated by a newline.
API that performs calculations:
In this example, we define a route that listens for POST requests to the '/add' endpoint. The function 'add' retrieves the values of 'a' and 'b' from the JSON data in the request using Flask's 'request.json' method. It then adds the two values together and returns a JSON response with the result.
API that uses JWT for authentication:
In this example, we use the Flask-JWT-Extended extension to implement authentication using JSON Web Tokens (JWT). We define a route for logging in with a username and password, which generates a JWT access token if the credentials are valid. We also define a protected route that requires a valid access token to access.
When a client makes a request to the protected endpoint, Flask-JWT-Extended checks the access token to ensure that it is valid and has not expired. If the token is valid, the client is allowed to access the protected endpoint and receive a JSON response.
API that handles file uploads:
In this example, we define a route that listens for POST requests to the '/upload' endpoint. The function 'upload' checks if a file was included in the request using Flask's 'request.files' method, and saves the file to a specified directory using Python's 'os' module.
API that uses SQLAlchemy to interact with a database:
In this example, we use the SQLAlchemy ORM to interact with a SQLite database. We define a 'User' model class with attributes for the user's name and email address. We also define two routes: one for retrieving a list of all users, and one for creating a new user.
When a client makes a GET request to the '/users' endpoint, the 'get_users' function retrieves all users from the database using SQLAlchemy's 'query.all()' method, and returns a JSON response with a list of all users' names and email addresses.
When a client makes a POST request to the '/users' endpoint with JSON data containing a user's name and email address, the 'create_user' function creates a new 'User' object and adds it to the database using SQLAlchemy's session management API. It then returns a JSON response with a success message.
API that uses JWT for authentication:
In this example, we use the Flask-JWT-Extended library to add authentication to our API using JSON Web Tokens (JWTs). We define a route '/login' that listens for POST requests containing a username and password in JSON format. The function 'login' checks the credentials against a predefined dictionary of users and passwords, and if they are valid, creates a JWT access token and returns it in a JSON response.
We also define a route '/protected' that is protected by the @jwt_required decorator. This decorator ensures that a valid JWT access token is included in the request, and if so, the 'protected' function retrieves the identity of the current user from the token and returns a JSON response with a personalized message.
API that uses Redis as a cache:
In this example, we use the Redis database as a cache to store key-value pairs. We define two routes: one for retrieving a value from the cache given a key, and one for setting a value in the cache given a key-value pair in JSON format.
When a client makes a GET request to the '/cache' endpoint with a query parameter 'key', the 'get_cache' function retrieves the value associated with that key from the Redis cache using the 'get' method. If the value exists, it is returned in a JSON response.
When a client makes a POST request to the '/cache' endpoint with JSON data containing a key-value pair, the 'set_cache' function sets that key-value pair in the Redis cache using the 'set' method. It then returns a JSON response with a success message.
API that uses SQLAlchemy to interact with a PostgreSQL database:
In this example, we use the SQLAlchemy library to interact with a PostgreSQL database. We define a Book class that inherits from the db.Model class, and has attributes for id, title, and author. We also define two routes: one for retrieving all books from the database, and one for adding a book to the database given a title and author in JSON format.
When a client makes a GET request to the '/books' endpoint, the 'get_books' function retrieves all books from the Book table using the query.all() method. It then returns a JSON response containing the id, title, and author of each book.
When a client makes a POST request to the '/books' endpoint with JSON data containing a title and author, the 'add_book' function creates a new Book object with those attributes and adds it to the session using the db.session.add() method. It then commits the changes to the database using the db.session.commit() method, and returns a JSON response with a success message.
API that sends email using Flask-Mail:
In this example, we use the Flask-Mail library to send email from a Gmail account. We define an app.config dictionary with the necessary configuration settings for the Gmail SMTP server, and a mail object that initializes the Mail extension with the app.
API that uses Flask-JWT-Extended for user authentication:
In this example, we use the Flask-JWT-Extended library for user authentication using JSON Web Tokens (JWT). We define an app.config dictionary with a secret key for JWT encoding, and a jwt object that initializes the JWT extension with the app.
We also define a list of users, each with a username and password. When a client makes a POST request to the '/login' endpoint with basic authentication containing a valid username and password, the 'login' function creates a JWT access token with the user's username as the identity, and returns it as a JSON response.
When a client makes a GET request to the '/protected' endpoint with a valid JWT access token in the Authorization header, the 'protected' function extracts the current user's identity using the get_jwt_identity() function, and returns a JSON response with a greeting message.
API that uses Flask-SocketIO for real-time communication:
In this example, we use the Flask-SocketIO library for real-time communication between the client and server using WebSockets. We define an app.config dictionary with a secret key for the app, and a socketio object that initializes the SocketIO extension with the app.
We also define a route '/' that renders an HTML template with a simple chat interface. When a client sends a message to the server using the 'message' event, the 'handle_message' function broadcasts the message to all connected clients using the emit() function with the 'message' event. The broadcast=True argument ensures that the message is sent to all clients except the sender.
API that uses Flask-RESTful for creating RESTful APIs:
In this example, we use the Flask-RESTful library for creating RESTful APIs. We define an app object, and initialize an Api object with the app. We then define a class HelloWorld that inherits from Resource, and has a GET method that returns a JSON response with a greeting message.
We add the HelloWorld resource to the API using the api.add_resource() function, and map it to the root URL '/'. When the client makes a GET request to the root URL, the API returns the JSON response from the HelloWorld resource.
API that uses Flask-SQLAlchemy for interacting with a database:
In this example, we use the Flask-SQLAlchemy library for interacting with a SQLite database. We define an app object, and set the app.config['SQLALCHEMY_DATABASE_URI'] to the URI of the SQLite database we want to use. We initialize a db object with the app.
We define a User class that inherits from db.Model, and has three columns: id (integer, primary key), username (string, unique, not null), and email (string, unique, not null). We also define a repr method for the User class to display the username in the representation.
We define a route '/users' that queries all the users from the User table using the User.query.all() function, and returns a JSON response with a list of user dictionaries.
API that uses Flask-Mail for sending email: