How to Create an API in Three Steps

Luke Russell
by Luke Russell on December 20, 2022 6 min read

Creating your own APIs can seem daunting if you’re new to the practice, but sticking to a design-first approach will keep you on the right track. A simple three-step process—design, verify, code—can increase your chances of building an API that benefits the people who use it.

Though it may be tempting to just start coding, spending the time upfront to design your API properly will save you time down the road by making your goals and evaluation criteria clearer.

Design

The first step in creating an API is designing the API. You start by discovering what problems your API needs to solve, and then you determine what endpoints and data are needed. The decisions you make during the design phase must be documented somewhere. REST APIs are most commonly described with the OpenAPI specification, so designing your API means creating an OpenAPI document for it.

While it may be tempting to write the code for the API and then generate the OpenAPI from the code, that’s about as effective as laying the bricks for a new house before creating the blueprints. Planning the API beforehand allows you to take input and feedback from users before it’s too late to make changes. (One part of this process is mocking, which we will discuss more in the next section.) Designing the API first will ensure you’re solving the right problems in the right way.

So, with your team by your side, you begin to plan out your API. The endpoints (or resources) you choose are the foundation of an API. You’ll need to decide what the API needs to expose and what descriptive names you should use. API URL best practices can guide you here, but it’s most important to maintain consistency throughout your entire API.

Each resource made into an endpoint can have actions performed on it using HTTP methods. For example, you may access contacts from your API. To retrieve a list of people, you could use the GET HTTP method on an endpoint called `contacts`. To add new contacts, you would use the POST method on the same endpoint, along with predetermined contact fields.

It can be helpful to visualize these endpoints, fields, and other details while you’re designing. Stoplight Studio helps you create OpenAPI documents without memorizing syntax. You should quickly specify and describe the available HTTP methods and responses for each of your endpoints. For an example of what modeling might look like, check out this video walkthrough of Stoplight Modeling on our YouTube channel.

Verify

Verification is the process of evaluating whether a system meets its design specifications. In this phase, you will collect feedback on your API design and make adjustments accordingly. For many people, just seeing endpoints isn’t enough to provide feedback; ideally, they would look at example API responses and might even start prototyping how the API will be consumed.

One solution for collecting user feedback on your design is API mocking. A mock API server is an imitation of your planned final API server. The server itself is real but temporary, and it is meant to respond with fake data. During the design process, it can be used to provide responses to requests. A mock API server can even supply dynamic mock data aligned with the expected type of response field. It’s also possible to fully stage mock APIs on public servers, allowing you to get feedback from a greater number of people.

After you have your OpenAPI document for your new API, create a mock server. Stoplight’s mock servers are powered by Prism, an open-source tool. One advantage of using a tool like Prism is that it generates dynamic examples based on your actual design, as opposed to static examples that could bias your API design approach.

Prism uses your OpenAPI document to determine your API’s endpoints, methods, and data. Then it serves mock data that fits the types specified in the API. For more detailed information about how Stoplight’s mocking process works, check out our documentation.

Code

Once you’ve tweaked your OpenAPI document with feedback collected via mocking, it’s time to build the real API. This is where many would start, but you have the advantage of much more confidence about how your API will be used over those approaching code-first.

You can use your preferred language to code the API. For readability, we’ll show Python using the Flask framework. The point is just to give you an idea of what API code would look like. Eager to learn more? Get a more extensive overview at our Python REST API tutorial.

The general format of an endpoint method using Flask looks like this:

```

@api.route('/YOUR-ENDPOINT', methods=['YOUR-HTTP-ACTION'])

def YOUR-HTTP-ACTION_YOUR-ENDPOINT():

  return json.dumps(RELEVANT_RESOURCE)

```

Below is the text of a file, named `flaskapi.py`, which can be run from the command line with `python flaskapi.py` to make the `GET /companies` request. 

 

```

from flask import Flask, json

companies = [{"id": 1, "name": "Company One"}, {"id": 2, "name": "Company Two"}]

api = Flask(__name__)

@api.route('/companies', methods=['GET'])

def get_companies():

  return json.dumps(companies)

if __name__ == '__main__':

    api.run()

```

It’s here that you would connect to your database, as well. Since this is in Python, you could use SQLite, a popular SQL database engine. Any additional application logic will also work with Flask, or any other framework you prefer.

Another option is to use Connexion to map the endpoints from your OpenAPI document to Python functions. One advantage to machine-readable definitions is that you can use them with many tools throughout the lifecycle, including those for mocking, data validation, contract testing, and generating documentation. For a variety of other tools to assist you along the way, like SDK generators, check out OpenAPI.Tools.

You’ve Got This—And We Can Help

Instead of diving headfirst into code, flopping out a half-useful API that doesn’t hold up in its first interactions in the real world, and then ending up writing a v2 a few months later, take a little time to design and verify your API before getting started. You can use Stoplight Platform (totally free—and it works with your existing repos) to create your OpenAPI documents with a visual editor. Then create your mock servers and publish documentation to get feedback from your team. With this simple method for a design-first approach, any of your API visions are within your reach.

Share this post

Stoplight to Join SmartBear!

As a part of SmartBear, we are excited to offer a world-class API solution for all developers' needs.

Learn More
The blog CTA goes here! If you don't need a CTA, make sure you turn the "Show CTA Module" option off.

Take a listen to The API Intersection.

Hear from industry experts about how to use APIs and save time, save money, and grow your business.

Listen Now