500 ошибка postman

I’m trying to set up a test where I make a POST request but getting a 500 Server Error​ (Response Body that I’m seeing is Unexpected ‘T’ [JSON]; Tests reporting «There was an error in evaluating the test script: SyntaxError: Unexpected token T in JSON at position 0») and so Tests should show Failed for all 5 of my tests. What can i do?

One of my tests isn’t even run it looks like:
tests[«Status code is 201 Created»] = responseCode.code === 201;

Thanks in advance for your help.
Tien.

asked Apr 11, 2017 at 23:23

Tien's user avatar

2

You can check that HTTP code is not 500 with following:

tests["Status code is not 500"] = responseCode.code != 500;

Is this what you’re looking for?

answered Apr 12, 2017 at 13:15

grinderX19's user avatar

grinderX19grinderX19

5645 silver badges13 bronze badges

3

Error 500 means either you are sending some invalid JSON in your request body or some issue with your server.
Could tell more by looking at the request and response body.

Do you have your test under any if condition? I don’t any reason why the test didn’t run except if you have any syntax error in test section.

answered Apr 12, 2017 at 7:20

Dinesh Kumar's user avatar

Dinesh KumarDinesh Kumar

1,67415 silver badges22 bronze badges

2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Open

Bysmyyr opened this issue

Mar 21, 2020

· 24 comments

Open

Postman api returns 500 and 504

#8213

Bysmyyr opened this issue

Mar 21, 2020

· 24 comments

Assignees

@davidespihernandez

Comments

@Bysmyyr

Postman API PUT to collections endpoint gives 500 and 504 and sometimes returns an empty body. We update the collections to 25 users from the ci run in wercker which runs 10 updates concurrently. Sometimes all they go through fine, sometimes there is one or two fail which is covered by retry logic but increasingly lately it fails so badly than 10 retries are not enough. Collections are quite big, about 600 requests altogether. It also generates double collections(some empty, some not).

500 {"error":{"name":"serverError","message":"Something went wrong with the server."}}

504:

<html>
<head><title>504 Gateway Time-out</title></head>
<body bgcolor="white">
<center><h1>504 Gateway Time-out</h1></center>
<hr><center>nginx</center>
</body>
</html>

@preethammavin

@Bysmyyr can you write to us at help@getpostman.com. Would want to take a deeper look at this, I would suggest breaking the collection down into smaller collections of size (preferably lesser than 25 MB) as I see it is timeout error there.

@abiancu

Trying to make a GET request to https://api.covid19api.com/summary but getting a 504 error. Was working fine on 05/02/2020

<title>504 Gateway Time-out</title>

504 Gateway Time-out


nginx/1.14.0 (Ubuntu)

@Bysmyyr

@abiancu Your error is not even closely related to this. This is about postman internal API, not using poistman for some other API

@mohitranka

@Bysmyyr — We have made few performance improvements to these endpoints in the last month. I’d like to know if you are still facing issues around big collection updates.

@galbarm

@mohitranka
I’m still facing the issue.
You can see more details in support ticket #60411

Specifically, for update collection request with body around 1MB, the «Something went wrong with the server.» error is returned after 1 minute.

Also note that collections API only operates on full collections.
You cannot update a single request/folder within a collection.
As a result, there is no workaround for this issue.

@Bysmyyr

@mohitranka Thanks for your reply. Our issues have went worse in last months.

@Raj-postman

Our team checked on this further after the comment @Bysmyyr — may I know if it helped?

@galbarm We haven’t heard back from you on the ticket. Just checking to see if the recent improvements helped?

@galbarm

Our team checked on this further after the comment @Bysmyyr — may I know if it helped?

@galbarm We haven’t heard back from you on the ticket. Just checking to see if the recent improvements helped?

Hi,
I can’t tell if it helped because my workaround was to delete-create the whole collection for each update instead of using the update API, and this is how my system currently works.
This is not perfect because a failure after delete but before the creation is dangerous, but I had no other option.

@galbarm

Seems like you have some regression that causes this error to now occur for every (large enough) request.
Even the delete-create workaround doesn’t help now.
You may also want to know that the request takes place even though an error is returned.
As a result and to deal with that, this is how our code currently looks like:

        case result if result.status == 200 => result.body[JsValue]

        //workaround the slow Postman servers. see https://github.com/postmanlabs/postman-app-support/issues/8213
        case result if result.status == 500 && result.body.contains("Something went wrong with the server") =>
          logger.debug("finishing with success (even though postman 500), because we've observed that the collection gets updated regardless of the error.")
          result.body[JsValue]

        case result => throw HttpResponseException(result)

Please try not to change anything, unless you actually fix it.

@RonMiltonPing

Seeing the same behavior. Our collection is about 3 MB, 300+ requests with a lot of documentation. Put call to Collections returns a 504 after a minute but the collection gets updated a few minutes later. Have not tried the delete-create approach yet.

@kszafran

We had to remove most of the descriptions from our collection to lower the overall size, and now we get 500s only sometimes… It’s still pretty disappointing.

@AndrewGuenther

I’m seeing the 500 behavior as well. My collection file is only 350KB and I get a 500 error 100% of the time, but the collection does actually update. Similar use case to the requester: We want to update a collection from within our CI system. Here’s the exact curl request:

curl -v --location -g --request PUT "https://api.getpostman.com/collections/$collection_uid" 
--header "X-Api-Key: $POSTMAN_API_KEY" 
--header 'Content-Type: application/json' 
--data-binary '@postman.json'

@juliehubs

I have also been seeing this issue, has there been any solution for this?
Thanks!

@kszafran

I our case (same company as the OP), this is still the workaround that we’re using:

We had to remove most of the descriptions from our collection to lower the overall size, and now we get 500s only sometimes… It’s still pretty disappointing.

We’ll be looking into alternative ways to publish our API documentation. For just making requests from the Postman app we can deal with no descriptions. I haven’t seen 500s in a long time now.

@AndrewGuenther

My workaround has been no longer using Postman 🤷‍♂️

@kszafran

@AndrewGuenther Have you switched to some alternative solution that you could recommend?

@AndrewGuenther

I’ve been using Paw and have been pretty happy with it so far.

@bpedro

Hey everyone, thanks for all your comments and patience with this issue.

We have been working on a new way of updating individual collection items (requests, folders, responses).

Please let me know if you’d be interested in testing the new endpoint.

@gbarmashiahflir

Hey everyone, thanks for all your comments and patience with this issue.

We have been working on a new way of updating individual collection items (requests, folders, responses).

Please let me know if you’d be interested in testing the new endpoint.

I’ll be happy to

@gbarmashiahflir

@bpedro Can I get access to the new endpoint? Our API is large and is suffering from serious issues when trying to update the whole collection.

@bpedro

Hi @gbarmashiahflir, thanks for your patience.

We are getting in touch with you privately with information about the individual collection items operations.

@abrunke

We have recently started to get 504 errors when retrieving the collection via the post API using Newman.

Newman logs are as follows

2022-10-27T12:02:27.091-07:00	error: collection could not be loaded

2022-10-27T12:02:27.091-07:00	Error fetching the collection from the provided URL. Ensure that the URL is valid.

2022-10-27T12:02:27.091-07:00	Error fetching collection, the provided URL returned status code: 504

On retrying this is fine but it does cause the test via Newman to fail which is annoying.

Any suggestions? I can share the URL privately if that helps

@bpedro

@davidespihernandez

Hi! Related to the PUT operation failing for big collections, we already have exposed an endpoint that allows updating collection individual items (requests, folders, and responses). You can find documentation and examples here: https://www.postman.com/postman/workspace/postman-public-workspace/collection/16473433-f2f0cb8f-609d-443f-913c-9831187c326e?ctx=documentation

In addition, we have been improving the performance of the PUT and POST collections endpoints, but there will always be a limitation… I mean, we won’t process a collection of 100MB in a single PUT. In case of huge collections, the recommendation is to split them into smaller ones or use the collection individual items endpoint if possible.

I need to test the 500 ‘internal server error’ but Need to test this new API with calls from postman. Does anyone know how to make a call that will trigger it? I’m not talking about setting up a mock or doing it from the dev side. I need to invoke 500 responses by making requests so I can verify that a 500 request is returned from this new server.

Solution 1:[1]

The 500 Internal Server Error is internal to your system and you will get it when there is some issue in your code.

If the code doesn’t has issues and you just want to get a 500 error status for testing then you can throw an exception like NullPointerException from your code.

Solution 2:[2]

the 500 error can be get by not passing necessary parameter in header eg x-api-key and also incorrect data in request as not accepted by server eg name an be Name

Dears ,

I am new to Python and flask . When I run the following code on Spyder I get the following message:

runfile('C:/Users/...../Desktop/Folders/..../BlockChain/Create Blockchain/Module 1 - Create a Blockchain/blockchain.py', wdir='C:/Users/...../Desktop/Folders/..../BlockChain/Create Blockchain/Module 1 - Create a Blockchain')
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) 

but when I want to run http://127.0.0.1:5000/get_chain on POSTMAN, I get the following message:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

I TOTALLY CONFUSED WHY? Here is my code:

import datetime
import hashlib
import json
from flask import Flask, jsonify, request

Part 1 — Building a Blockchain

class Blockchain:

    def __init__(self):
        self.chain = []
        self.create_block(proof = 1, previous_hash = '0')

    def create_block(self, proof, previous_hash):
        block = {'index': len(self.chain) + 1,
                 'timestamp': str(datetime.datetime.now()),
                 'proof': proof,
                 'previous_hash': previous_hash}
        self.chain.append(block)
        return block

    def get_previous_block(self):
        return self.chain[-1]

    def proof_of_work(self, previous_proof):
        new_proof = 1
        check_proof = False
        while check_proof is False:
            hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()
            if hash_operation[:4] == '0000':
                check_proof = True
            else:
                new_proof += 1
        return new_proof

    def hash(self, block):
        encoded_block = json.dumps(block, sort_keys = True).encode()
        return hashlib.sha256(encoded_block).hexdigest()

    def is_chain_valid(self, chain):
        previous_block = chain[0]
        block_index = 1
        while block_index < len(chain):
            block = chain[block_index]
            if block['previous_hash'] != self.hash(previous_block):
                return False
            previous_proof = previous_block['proof']
            proof = block['proof']
            hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()
            if hash_operation[:4] != '0000':
                return False
            previous_block = block
            block_index += 1
        return True

# Creating a Web App

    app = Flask(__name__)

# Creating a Blockchain

    blockchain = Blockchain()

# Mining a new block

    @app.route('/mine_block', methods = ['GET'])

    def mine_block():
        previous_block = blockchain.get_previous_block()
        previous_proof = previous_block['proof']
        proof = blockchain.proof_of_work(previous_proof)
        previous_hash = blockchain.hash(previous_block)
        block = blockchain.create_block(proof, previous_hash)
        response = {'message': 'Congratulations, you just mined a block!',
                    'index': block['index'],
                    'timestamp': block['timestamp'],
                    'proof': block['proof'],
                    'previous_hash': block['previous_hash']}
        return jsonify(response), 200

# Getting the full Blockchain

    @app.route('/get_chain', methods = ['GET'])
    def get_chain():
        response = {'chain': blockchain.chain,
                    'length': len(blockchain.chain)}
        return jsonify(response), 200

# Checking if the Blockchain is valid

    @app.route('/is_valid', methods = ['GET'])
    def is_valid():
        is_valid = blockchain.is_chain_valid(blockchain.chain)
        if is_valid:
            response = {'message': 'All good. The Blockchain is valid.'}
        else:
            response = {'message': 'Houston, we have a problem. The Blockchain is not valid.'}
        return jsonify(response), 200


# Running the app

    app.run(host='0.0.0.0', port=5000)

Я создаю API, используя flask для сети
у меня уже есть база данных, и запрос GET работает, но когда я пытаюсь выполнить POST, он дает мне эту ошибку

500 INTERNAL SERVER ERROR

Это код, который я написал

#User_schema
class UserSchema(ma.Schema):
 class Mata:
  fields = ('id', 'name', 'Email', 'Pass', 'Phone', 'Department', 'Major')

#init_schema
user_schema = UserSchema()
users_schema = UserSchema(many=True)

#create user
@app.route('/user', methods=['POST'])
def add_User():
 #id = request.json['id']
 name = request.json['name']
 Email = request.json['Email']
 Pass = request.json['Pass']
 #Phone = request.json['Phone']
 Department = request.json['Department']
 Major = request.json['Major']

 new_user = User(name, Email, Pass, Department, Major)
 db.session.add(new_user)
 db.session.commit()

 return user_schema.jsonify(new_user)

Это запрос, который я добавил на почту человека

{
    "name": "User 1",
    "Email": "User1@.com",
    "Pass": "qq1",
    "Phone": "0551",
    "Department": "IT 1",
    "Major": "IT 1"
}

Я также использую локальный сервер
я посмотрел на другие ссылки, и все просят журналы, и если я не ошибаюсь, я думаю, что я получаю их от

View > Developer > Show DevTools > Console

И это скриншот журнала: (я думаю)

В чем именно проблема я не понимаю

Обновлено: Вот полный код:

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)

class User (db.Model):
 id = db.Column(db.Integer,primary_key=True)
 name = db.Column(db.String(30))
 Email = db.Column(db.String(30))
 Pass = db.Column(db.String(30))
 Phone = db.Column(db.Integer)
 Department = db.Column(db.String(30))
 Major = db.Column(db.String(30))
 meeting = db.relationship('Meeting', backref='creator')
 meetingroom = db.relationship('MeetingRoom', backref='reserver')

    def _init_(self, name, Email, Pass, Phone, Department, Major):
  self.name = name
  self.Email = Email
  self.Pass = Pass
  self.Phone = Phone
  self.Department = Department
  self.Major = Major

class MeetingRoom (db.Model):
 mrid = db.Column(db.Integer,primary_key=True)
 reserver_id = db.Column(db.Integer, db.ForeignKey('user.id'))
 #meetingm = db.relationship('Meeting', backref='roomno')
 mid = db.Column(db.Integer, db.ForeignKey('meeting.Mid'))

class Meeting (db.Model):
 Mid = db.Column(db.Integer,primary_key=True)
 Mname = db.Column(db.String(100))
 Des = db.Column(db.String(100))
 Date = db.Column(db.String(20))
 creator_id = db.Column(db.Integer, db.ForeignKey('user.id'))
 meetingroomm = db.relationship('MeetingRoom', backref='mroom')
 #roomno_id = db.Column(db.Integer, db.ForeignKey('meetingroom.mrid')


##json 
@app.route('/users', methods=['GET'])
def getuser():
 users = User.query.all()
 output = []
 for user in users:
  user_data = {}
  user_data['id'] = user.id
  user_data['name'] = user.name
  user_data['Email'] = user.Email
  user_data['Pass'] = user.Pass
  user_data['Phone'] = user.Phone
  user_data['Department'] = user.Department
  user_data['Major'] = user.Major
  output.append(user_data)
 return jsonify({'users' : output})


#User_schema
class UserSchema(ma.Schema):
 class Mata:
  fields = ('id', 'name', 'Email', 'Pass', 'Phone', 'Department', 'Major')

#init_schema
user_schema = UserSchema()
users_schema = UserSchema(many=True)

#create user
@app.route('/user', methods=['POST'])
def add_User():
 #id = request.json['id']
 name = request.json['name']
 Email = request.json['Email']
 Pass = request.json['Pass']
 #Phone = request.json['Phone']
 Department = request.json['Department']
 Major = request.json['Major']

 new_user = User(name, Email, Pass, Department, Major)
 db.session.add(new_user)
 db.session.commit()

 return user_schema.jsonify(new_user)

#meeting_schema
class MeetingSchema(ma.Schema):
 class Mata:
  fields = ('Mid', 'Mname', 'Des', 'Date', 'creator_id')

#init_schema
meeting_schema = MeetingSchema()
meetings_schema = MeetingSchema(many=True)

#create meeting
@app.route('/meeting', methods=['POST'])
def add_meeting():
 Mname = request.json['Mname']
 Des = request.json['Des']
 Date = request.json['Date']


 new_meeting = Meeting(Mname, Des, Date)
 db.session.add(new_meeting)
 db.session.commit()

 return user_schema.jsonify(new_meeting)


if __name__ == '__main__':
 app.run(debug=True)

2-е Обновлено: журнал консоли

После добавления ошибки определения:

cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) database is locked
[SQL: INSERT INTO user (name, "Email", "Pass", "Phone", "Department", "Major") VALUES (?, ?, ?, ?, ?, ?)]
[parameters: ('User 1', 'User1@.com', 'qq1', '0551', 'IT 1', 'IT 1')]
(Background on this error at: http://sqlalche.me/e/e3q8)

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • 500 ошибка dns
  • 500 непредвиденная ошибка exchange
  • 500 мэйл ошибка что это
  • 500 критическая ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии