3 Ways to create an API in Python

February 05, 2024
Written by
Twilion
Reviewed by
Twilion

3 Ways to create an API in Python

Creating an API (Application Programming Interface) in Python can be a straightforward process, thanks to various frameworks and libraries available. In this post, we'll explore three popular methods to set up a web API in Python: Flask, FastAPI, and Django Rest Framework.

Prerequisites

Flask

Flask is a lightweight framework that can be used to develop web applications and APIs. To create an API using Flask, start by creating a new directory for your application.

mkdir flask-example
cd flask-example

Now, create a virtual environment using the following command:

python -m venv .venv

This will create a new directory .venv in our project folder for our virtual environment.

Install Flask with the following command.

pip install flask

Now, to create our API, create a new file main.py and add the following:

from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/greet', methods=['GET'])
def greet():
    return jsonify(message="Ahoy, World!")
if __name__ == '__main__':
    app.run(debug=True)

To run our application, open a new window in your terminal and run the command to execute the script:

python main.py

You'll have a basic API that returns a greeting message when accessed at http://localhost:5000/api/greet .

You can test this either in your browser, or by sending a GET request in Postman to the http://localhost:5000/api/greet endpoint. You will see a JSON response:

{
	"Message": "Ahoy, World!"
}
"Ahoy, world" stylized message

FastAPI

FastAPI is a modern, fast (high-performance) web framework based on standard Python type hints. It's particularly suitable for building APIs and is known for its speed.

Create a new directory for the FastAPI project.

mkdir fastapi-example
cd fastapi-example

Now, create a virtual environment using the following command:

python -m venv .venv

This will create a new directory .venv in our project folder.

Now install FastAPI and Uvicorn (an ASGI server)

pip install fastapi uvicorn

Let’s code a simple API, create a new file main.py and add the following code:

from fastapi import FastAPI
app = FastAPI()
@app.get("/api/greet")
def greet():
    return {"message": "Ahoy, World!"}
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

To run the FastAPI app, execute the script, by running the command in your terminal:

python main.py

You now have a basic API that returns a greeting message when accessed at http://localhost:8000/api/greet

Again you can either use Postman, your browser or even test it in the terminal by using curl to test your API by sending a GET request.

Here is a curl example:

curl http://localhost:8000/api/greet

You should get a JSON response from the API:

{"message":"Ahoy, World!"}
Stylized "Ahoy, world" message

Also, you get Interactive API documentation automatically!

Head over to http://localhost:8000/docs in your browser to access them.

FastAPI Documentation overview

Django Rest Framework (DRF)

Django Rest Framework is a powerful and flexible toolkit for building Web APIs and is built on top of the Django framework.

Just like the previous two examples, start by creating a new directory for your application.

mkdir django-api-example
cd django-api-example

Now, create a virtual environment using the following command:

python -m venv .venv

This will create a new directory .venv in our project folder.

Install Django and DRF.

pip install django djangorestframework

Start a new Django project(django-api) and create a new app(api).

django-admin startproject djangoApiExample .
python manage.py startapp api

Now let’s write some code.

First, set up the model in models.py in the api directory

# api/models.py
from django.db import models
class Greeting(models.Model):
    message = models.CharField(max_length=255)

Next, create a file named serializers.py inside the api folder and add:

# api/serializers.py
from rest_framework import serializers
from .models import Greeting
class GreetingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Greeting
        fields = ['id', 'message']

Set up the API view in views.py.

# api/views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import Greeting
from .serializers import GreetingSerializer
@api_view(['GET'])
def greet(request):
    greeting = Greeting(message="Ahoy, World!")
    serializer = GreetingSerializer(greeting)
    return Response(serializer.data)

Now to set up the URL routing, create a file named urls.py inside the api folder and add:

# api/urls.py
from django.urls import path
from . import views
urlpatterns = [
    path('api/greet/', views.greet, name='greet-api'),
]

Include your app's URLs into the main project. In django-api-example/urls.py, you will need to include the app's URLs:

#djangoApiExample
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('api.urls')),
]

Update Django settings, add rest_framework and api to the INSTALLED_APPS list in django-api-example/settings.py.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'api',
]

Now let’s run our API. Run migrations and start the server.

In your terminal, run the following command, make sure you are in the django-api-example directory.

python manage.py migrate

Start the server.

python manage.py runserver

Now, if you navigate to http://localhost:8000/api/greet/ in your web browser, you should see:

Django REST framework documentation

You can also add the JSON format parameter to the endpoint and use curl or Postman to try it out. Here is an example of a GET request with format parameter in the Postman Visual Studio Code extension.

Postman Visual Studio Code extension screenshot

Conclusion

Whether you're looking for the simplicity of Flask, the speed of FastAPI, or the robustness of Django Rest Framework, Python offers a range of options to quickly and efficiently develop APIs. Your choice depends on the project requirements, your familiarity with the frameworks, and the features you need, let’s say you just started coding and looking to build your first API, try Flask, but if you want automatic API documentation with ease of use and speed - go for FastAPI. Whatever you choose, happy coding!

Rishab Kumar is a Developer Evangelist at Twilio and a cloud enthusiast. Get in touch with Rishab on Twitter @rishabk7 and follow his journey in tech on cloud, DevOps, and DevRel adventures at youtube.com/@rishabincloud .